718. Maximum Length of Repeated Subarray

题目:

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;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值