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
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>
using namespace std;
class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
int N=A.size(),M=B.size();
vector<int> cur(M,0);
vector<vector<int> >dp(N,cur);
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
if(i==0||j==0)
if(A[i]==B[j])dp[i][j]=1;
else{
if(A[i]==B[j])
dp[i][j]=max(dp[i][j],dp[i-1][j-1]+1);
else
dp[i][j]=0;
}
}
}
return dp[N-1][M-1];
}
};
int main(int argc, char const *argv[])
{
int n,m;
std::vector<int> A;
std::vector<int> B;
cin>>n>>m;
A.assign(n,0);
B.assign(m,0);
for (int i = 0; i <n; ++i)
scanf("%d",&A[i]);
for (int i = 0; i <m; ++i)
scanf("%d",&B[i]);
int a=Solution().findLength(A,B);
cout<<a<<endl;
system("pause");
return 0;
}
简析:dp[i][j] 表示A[i]与B[j]之前的连续的最大长度。
只要A[i]!=B[j]那么dp[i][j]=0
当i=0或者j=0时,dp[i][j]与前面无关,如果A[i]==B[j],dp[i][j]=1;
剩余的i,j用状态方程:
A[i]=B[j]时:
dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + 1);
A[i]!=B[j]时
dp[i][j]=0