leetcode010-Maximum Length of Repeated Subarray(LCS動態規划)


Given two integer arrays A and B, return the maximum length of an subarray that appears in both arrays.

Example 1:

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

Note:

  1. 1 <= len(A), len(B) <= 1000
  2. 0 <= A[i], B[i] < 100

思路: 狀態lengthEndsAtAB[i][j]表示以A的第i個字符,B的第j個字符結尾的最長重復子串的長度

         狀態轉移 lengthEndsAtAB[i][j] = (A[i-1] == B[j-1]) ? lengthEndsAtAB[i-1][j-1]+1:0

注意:1.A[i-1]表示的是A的第i個字符,A從0開始計數,同理B。 lengthEndsAtAB[i][j]從1開始計數

           2.一旦A[i-1] != B[j-1]即可設為0,因為最長的重復子串要求連續,如果當前位置已經發生中斷,則計數不會再從這個點開始增加。而在檢測到A的前i個字符,B的前j個字符的狀態時,當中能夠生成的最長重復子串的長度以被lengthEndsAtAB[i-1][j-1]所記錄。這個點必須設為0,否則會影響lengthEndsAtAB[i+1][j+1]的值。


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

當給出的不是兩個整數序列,而是兩個字符串時,這個問題就是經典的Longest Common Substring
int longestSubstring(string x, string y) {
        vector<vector<int>> max(x.size()+1,vector<int>(y.size()+1,0));
        int result = 0;
        for (int i = 1; i < x.size()+1; i++) {
            for (int j = 1; j < y.size()+1; j++) {
                max[i][j] = x[i-1]==y[j-1]?max[i-1][j-1]+1:0;
                result = result<max[i][j]?max[i][j]:result;
            }
        }
        return result;
    }



注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com