- descrption
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
- 解题思路
求最长子串长度,利用动态规划算法。找到动态规划的状态和状态转移方程就可以解决问题。令C[i][j]表示以A[i]和b[j]结尾的最长字串长度,如果A[i]不等于B[j],那么C[i][j]就等于0,如果相等,那么C[i][j]就等于以A[i-1]和B[j-1]结尾的最长子串长度+1。
C[i][j] = A[i]==B[j]?C[i−1][j−1]+1:0
- 代码如下
class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
vector<vector<int>> C(A.size()+1, vector<int>(B.size()+1, 0));
int ans = 0;
for(int i = 1; i < A.size() + 1; i++){
for(int j = 1; j < B.size() + 1; j ++){
if(A[i-1] == B[j-1]) {
C[i][j] = C[i-1][j-1] + 1;
}
if(ans < C[i][j]){
ans = C[i][j];
}
}
}
return ans;
}
};
如有错误请指出,谢谢!