第16周Maximum Length of Repeated Subarray

Maximum Length of Repeated Subarray

Leetcode algorithms problem 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.

  • 例子

    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].

  • 思路

    dp[i][j] = a[i] == b[j] ? dp[i + 1][j + 1] : 0;
    dp[i][j] : max lenth of common subarray start at a[i] & b[j];

代碼

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

時間複雜度: O(mn)
空間複雜度: O(n)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章