Number.718——最長重複子數組

題目鏈接:https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray/

給兩個整數數組 A 和 B ,返回兩個數組中公共的、長度最長的子數組的長度。

輸入:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
輸出: 3
解釋:
長度最長的公共子數組是 [3, 2, 1]。

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

dp[i][j]表示以A[i-1]和B[j-1]結尾的公共子數組的長度,當A[i-1] == B[j-1]時,dp[i][j] = dp[i - 1][j - 1] + 1; 否則,dp的值不變
這裏dp數組的長度值比A和B的要大一,並且從1開始計算。最後返回dp數組的最大值即可。

  3 2 1 4 7
1 0 0 1 0 0
2 0 1 0 0 0
3 1 0 0 0 0
2 0 2 0 0 0
1 0 0 3 0 0
class Solution {
    public int findLength(int[] A, int[] B) {
        int lenA = A.length;
        int lenB = B.length;
        int[][] dp = new int[lenA + 1][lenB + 1];
        int result = 0;
        for (int i = 1; i < lenA + 1; i++){
            for (int j = 1; j < lenB + 1; j++){
                if (A[i - 1] == B[j - 1]){
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    result = Math.max(result, dp[i][j]);
                }
            }
        }
        return result;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章