Week11
Problem–Medium–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
题目解析:
这是一道典型的动态规划题目,即两段字符串中找最长公共子串。首先,我们需要寻找原问题的子问题,原问题求两段长度分别为m,n的字符串的最长公共子序列,那么,我们可以先求前n-1与m-1长的字符串的最长公共子序列,看以第n-1与m-1结尾的序列的最长公共子序列长度是多少,假设第n与m个字符也相等,那么只需在前面的基础上加1即可,那么我们就得到了一个状态转移方程: 初始化:dp[i][j] = 0
(i=0||j=0) 转移方程:dp[i][j] = dp[i – 1][j – 1] + 1
(A[i] = B[j])
dp[i][j] = dp[i – 1][j – 1]
(A[i] != B[j])
代码:
class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {
int ** dp = new int *[A.size() + 1];
for (int i = 0; i <= A.size(); i++) {
dp[i] = new int[B.size() + 1];
}
for (int i = 0; i <= A.size(); i++) {
for (int j = 0; j <= B.size(); j++) {
dp[i][j] = 0;
}
}
int Max = 0;
for (int i = 1; i <= A.size(); i++) {
for (int j = 1; j <= B.size(); j++) {
if (A[i - 1] == B[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = 0;
}
if (Max < dp[i][j]) {
Max = dp[i][j];
}
//cout << "dp " << i << " " << j << " = " <<dp[i][j] << endl;
}
}
return Max;
}
};