题目:
Given two integer arrays nums1
and nums2
, return the maximum length of a subarray that appears in both arrays.
Example 1:
Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] Output: 3 Explanation: The repeated subarray with maximum length is [3,2,1].
Example 2:
Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0] Output: 5
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 100
思路:
字符串dp题,本题用的dp矩阵是m乘n的,因此dp[i][j]代表了str1从从到 i 所构成的字符串和str2从0到 j 构成的字符串的公共最长子数组。递推公式很简单,子要当前str1[i] 和str2[j]相等,dp[i][j]就等于dp[i - 1][j - 1] + 1,这个很好理解,如果当前两个字母相等,那么自然是加一。初始化则是只要字母相等,赋值为1即可,在初始化的时候也要记得记录最大值,否则是可能漏下正确答案的,比如[1,2,3,2,8] [5,6,1,4,7],如果在初始化不记录,那么答案就变成了0。
代码:
class Solution {
public:
int findLength(vector<int>& a, vector<int>& b) {
int m = a.size(), n = b.size();
vector<vector<int>> f(m, vector<int>(n));
f[0][0] = a[0] == b[0] ? 1 : 0;
int ans = 0;
for (int i = 1; i < m; i++) {
if (a[i] == b[0])
f[i][0] = 1;
ans = max(f[i][0], ans);
}
for (int j = 1; j < n; j++) {
if (b[j] == a[0])
f[0][j] = 1;
ans = max(f[0][j], ans);
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
if (a[i] == b[j]) {
f[i][j] = f[i - 1][j - 1] + 1;
}
ans = max(ans, f[i][j]);
}
}
return ans;
}
};