给定两个整数数组,求两个数组的最长的公共子数组的长度。子数组是连续的,比如[1,3,5,7,9]的子数组有[1,3],[3,5,7]等等,但是[1,3,7]不是子数组
数据范围:两个数组的长度都满足 ,数组中的值都满足
[1,2],[1,2]
2
最长的公共子数组是[1,2]
[1,2,5,5,7,8],[2,5,7,8,5]
3
最长的公共子数组是[5,7,8]
[1,2],[1,3,2]
1
最长的公共子数组是[1]
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param A int整型一维数组 * @param B int整型一维数组 * @return int整型 */ public int longestCommonSubarry (int[] A, int[] B) { // write code here int[][] dp = new int[A.length + 1][B.length + 1]; int maxLen = 0; for(int i = 1; i <= A.length; i++){ for(int j = 1; j <= B.length; j++){ if(A[i - 1] == B[j - 1]){ dp[i][j] = dp[i - 1][j - 1] + 1; } maxLen = Math.max(maxLen, dp[i][j]); } } return maxLen; } }
package main import _"fmt" /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param A int整型一维数组 * @param B int整型一维数组 * @return int整型 */ func longestCommonSubarry( A []int , B []int ) int { m,n:=len(A),len(B) mat:=make([][]int,m+1) for i,_:=range mat{ mat[i]=make([]int,n+1) } ans:=0 for i:=0;i<m;i++{ for j:=0;j<n;j++{ if A[i]==B[j]{ mat[i+1][j+1]=mat[i][j]+1 if mat[i+1][j+1]>ans{ ans=mat[i+1][j+1] } } } } return ans }