718. Maximum Length of Repeated Subarray

标签(空格分隔): leetcode

1.原题

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

2. 分析

  • 采用动态规划的方法, 有2个数组, 以dp[i][j]表示以A[ i ] 和 B[ j ]结尾的最长的字符串
  • 如果A[i] == B[j] 那么以A[ i ] 和 B[ j ]结尾的最长的字符串等于A[ i – 1][ j – 1]的最长的字符串长度加上这一位, dp[i][j]=dp[i1][j1]+1
  • 考虑越界问题以及初始化无意义的边缘
  • 考虑怎么初始化二维的动态数组才不会出错。

3. 代码

class Solution {
public:
    int findLength(vector<int>& A, vector<int>& B) {
        int len1 = A.size();
        int len2 = B.size();
        if (len1 == 0 || len2 == 0)
            return 0;
        int **dp = new int*[len1 + 1];
        int max = -1;

        for (int i = 0; i <= len1; i++) {
            dp[i] = new int[len2 + 1];
            for (int j = 0; j <= len2; j++) {
                if (i == 0 || j == 0) {
                    dp[i][j] = 0;
                }
                else {
                    if (A[i - 1] == B[j - 1]) {
                        dp[i][j] = dp[i - 1][j - 1] + 1;
                    }
                    else {
                        dp[i][j] = 0;
                    }
                    if (max < dp[i][j]) {
                        max = dp[i][j];
                    }
                }
            }
        }
        return max;
    }
};
点赞