最长重复子数组

718. 最长重复子数组

Screenshot from 2020-07-01 14-40-02

思路

这道题类似最长公共子序列,可以使用动态规划来解决。

image.png

代码

二维的

/**
 * 1 <= len(A), len(B) <= 1000
 * 0 <= A[i], B[i] < 100
 */
class Solution {
    public int findLength(int[] A, int[] B) {
        int row = A.length;
        int col = B.length;

        int[][] dp = new int[row + 1][col + 1];
        int res = 0;
        
        for(int i = 1; i <= row; i++){
            for(int j = 1; j <= col; j++){
                if(A[i - 1] == B[j - 1]){
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    if(res < dp[i][j]){
                        res = dp[i][j];
                    }
                }
                else{
                    dp[i][j] = 0;
                }
            }
        }
        return res;
    }
}

一维的

/**
 * 1 <= len(A), len(B) <= 1000
 * 0 <= A[i], B[i] < 100
 */
class Solution {
    public int findLength(int[] A, int[] B) {
        int row = A.length;
        int col = B.length;

        int[] dp = new int[col + 1];
        int res = 0;

        for(int i = 1; i <= row; i++){
            //从后向前遍历,防止dp[j-1]的值被冲掉
            for(int j = col; j >= 1; j--){
                if(A[i - 1] == B[j - 1]){
                    dp[j] = dp[j - 1] + 1;
                }
                else{
                    dp[j] = 0;
                }
                res = Math.max(res, dp[j]);
            }
        }
        return res;
    }
}
posted @ 2020-07-01 23:00  zjy4fun  阅读(219)  评论(0编辑  收藏  举报