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
Approach
题目大意:找A和B中最长公共连续子串
思路方法:动态规划,此题类似于最长公共子序列,难度较低。
Code
class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
vector<vector<int>> grid(A.size()+1, vector<int>(B.size()+1, 0));
int maxn = 0;
for (int i = 0; i < A.size(); i++) {
for (int j = 0; j < B.size(); j++) {
if (A[i] == B[j]) {
grid[i + 1][j + 1] = grid[i][j] + 1;
maxn = max(maxn, grid[i + 1][j + 1]);
}
}
}
return maxn;
}
};