Given two integer arrays A
and B
, return the maximum length of an subarray that appears in both arrays.
简单dp
class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
int dp[1024][1024];
int s_a = A.size();
int s_b = B.size();
for(int i = 0; i <= s_a; i++){
dp[i][0] = 0;
}
for(int i =0; i <= s_b; i++){
dp[0][i] = 0;
}
int max_length = 0;
for(int i = 1; i <= s_a; i++){
for(int j = 1; j <= s_b; j++){
if (A[i-1] == B[j-1]){
dp[i][j] = dp[i-1][j-1] + 1;
if(dp[i][j] > max_length){
max_length = dp[i][j];
}
}
else{
dp[i][j] = 0;
}
}
}
return max_length;
}
};