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
题意:有两个数组,求两数组的最长公共子串。
此处应注意最长公共子序列与最长公共子串的区别。前者子序列可以不连续,而后者必须是连续的。比如字符串,abcad与字符串acadb的最长公共子序列是acad,而最长公共子串是cad。
最长公共子序列状态转移方程:
最长公共子串状态转移方程:
因为如果xi!=yj,那么又得重新来算,因为在xi和yj处不能连起来,所以必须归0,重新再算。因为最长的子串可能出现在字符串中间的位置,所以必须边求c[i][j]边求最大值。
代码:
class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
vector<vector<int> > l(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])
l[i][j]=l[i-1][j-1]+1;
ans=max(ans,l[i][j]);
}
}
return ans;
}
};