Maximum Length of Repeated Subarray

2018/1/20 posted in  leetcode

运用了动态规划,从A的尾部,来遍历B。

class Solution {
public:
    int findLength(vector<int>& A, vector<int>& B) {
        int m = A.size(), n = B.size();
        if (!m||!n) {
            return 0;
        }
        vector<int> dp(n+1); //要比B的长度多一位,在下面j=为n-1时需要获取dp[j+1]的值
        int res = 0;
        for (int i = m-1; i>=0; i--) {
            for (int j = 0; j<n; j++) {
                dp[j] = A[i]==B[j] ? dp[j+1]+1 : 0;
                res = max(res, dp[j]);
            }
        }
        return res;
    }
};