title
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].
solution
dp, 求A和B最长公共subarray
class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
vector<vector<int>> dp(A.size(), vector<int>(B.size(), 0));
int res = 0;
for (int i = 0; i < A.size(); i++) {
for (int j = 0; j < B.size(); j++) {
if (A[i] == B[j]) {
if (i > 0 && j > 0) {
dp[i][j] = dp[i - 1][j - 1] + 1;
res = max(res, dp[i][j]);
}
else {
dp[i][j] = 1;
}
}
else {
dp[i][j] = 0;
}
}
}
return res;
}
};