[leetcode]718. Maximum Length of Repeated Subarray

[leetcode]718. Maximum Length of Repeated Subarray


Analysis

今天被微博上的孙艺兴bot笑死,哈哈哈哈哈—— [每天刷题并不难0.0]

Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.
在这里插入图片描述

Explanation:

dp[i][j] denotes the maximum common subarrary ending with A[i] and B[j],
thus dp[i][j] = A[i-1]==B[j-1]?1+dp[i-1][j-1]:0

Implement

class Solution {
public:
    int findLength(vector<int>& A, vector<int>& B) {
        int a = A.size();
        int b = B.size();
        vector<vector<int>> dp(a+1, vector<int>(b+1));
        int res = 0;
        for(int i=1; i<=a; i++){
            for(int j=1; j<=b; j++){
                if(A[i-1] == B[j-1])
                    dp[i][j] = 1+dp[i-1][j-1];
                res = max(res, dp[i][j]);
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/85111863