Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.
Example 1:
Input:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
Output: 3
Explanation:
The repeated subarray with maximum length is [3, 2, 1].
Note:
1 <= len(A), len(B) <= 1000
0 <= A[i], B[i] < 100
找出两个数组中重复部分子串的最大长度
思路:
虽然DP思路不是最快的,但是好理解。
有binary search + hash rolling的方法在线性时间复杂度,但是估计不会第一时间想到,还是用DP吧。
dp[i][j]表示A的0~i部分和B的0~j部分重复子串的最大长度。A中以i 结尾, B中以j 结尾。必须包含结尾的数字,但可以不包含开头。
注意重复子串应该是连续的,因为必须包含结尾的数字,当A[i] != B[j]时,显然不是重复子串,dp[i][j] = 0
当A[i] == B[j]时,就要看以它们前面一位数字结尾的重复子串的最大长度。
dp[i][j] = dp[i-1][j-1] + 1
但是注意最大长度不一定是在dp数组的结尾处出现的,需要中间持续更新最大值。
public int findLength(int[] A, int[] B) {
if(A == null || B == null) {
return 0;
}
int m = A.length;
int n = B.length;
int[][] dp = new int[m][n];
int result = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(A[i] == B[j]) {
dp[i][j] = ((i>0 && j>0) ? dp[i-1][j-1]:0) + 1;
} else {
dp[i][j] = 0;
}
result = Math.max(result, dp[i][j]);
}
}
return result;
}