718. Maximum Length of Repeated Subarray

718. 最长重复子数组

Posted by bbkgl on July 1, 2020

故国三千里

深宫二十年

动态规划,用dp[i][j]表示以A[i]以及B[j]为结尾的子串的公共串的长度。则很显然有公式:

dp[i][j] = A[i] == B[j] ? dp[i-1][j-1] + 1 : 0;

所以代码也很简短,复杂度O(N^2),完全可以接受!

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