版权声明:本文为博主原创文章,欢迎转载!转载请保留原博客地址。 https://blog.csdn.net/grllery/article/details/88255407
718. Maximum Length of Repeated Subarray
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
题目:数组A
、B
中相同子串的最大长度。
思路:动态规划。如果A
,B
中的某个子数组相同,假设是在位置A[i..]
,B[j..]
,用dp[i][j]
表示以A[i]
,B[j]
开头的子数组相同部分的长度,那么当A[i]=B[j]
时,以A[i]
,B[j]
开头的子数组的相同部分的长度由A[i+1]
,B[j+1]
开头的子数组的相同部分的长度决定(dp[i+1][j+1]
)。状态转移矩阵为dp[i][j] = dp[i+1][j+1] + 1
,每次更新dp[i][j]
时,同时更新最大长度。
class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
int lena = A.size();
int lenb = B.size();
vector<vector<int>> dp(lena+1, vector<int>(lenb+1));
int res = 0;
for(int i = lena-1; i >= 0 ; --i){
for(int j = lenb-1; j >=0; --j){
if(A[i] == B[j]){
dp[i][j] = dp[i+1][j+1] + 1;
res = max(res, dp[i][j]);
}
}
}
return res;
}
};