1 题目
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
2 尝试解
2.1 分析
求最长公共子串,与公共子序列不同的是,子串必须是连续的。所以对于A[i]==B[j],dp[i][j] = 1+dp[i-1][j-1],否则dp[i][j]=0。即dp[i][j]表示的是以A[i]和B[j]结尾的最长公共子串的长度。
2.2 代码
class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
vector<vector<int>> saver(A.size(),vector<int>(B.size(),0));
int result = 0;
for(int i = 0; i < A.size(); i++){
for(int j = 0; j < B.size(); j++){
if(A[i]==B[j]){
saver[i][j] = (i*j?saver[i-1][j-1]:0)+1;
result = max(result,saver[i][j]);
}
}
}
return result;
}
};
3 标准解
class Solution {
public:
int findLength(vector<int>& a, vector<int>& b) {
int m = a.size(), n = b.size();
if (!m || !n) return 0;
vector<int> dp(n + 1);
int res = 0;
for (int i = m - 1; i >= 0; i--) {
for (int j = 0; j < n; j++) {
res = max(res, dp[j] = a[i] == b[j] ? 1 + dp[j + 1] : 0);
}
}
return res;
}
};