Leetcode 718 - Maximum Length of

2018-06-26  本文已影响91人  BlueSkyBlue

题目:

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

Input:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
Output:3
Explaination:
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


思路:

该题可以用动态规划的思想解决。因此需要确定状态数组的意义以及状态方程。

假设有两个字符串str1str2

dp[i][j] = dp[i-1][j-1] + 1

状态方程的意义:str1中第i个字符和str2中第j个字符相等的时候,str1中前i-1个字符串和str2中前j-1个字符串的最大共有字符串的长度+1。

在计算出dp[i][j]的时候需要比较最大值(max),因为题目最终要的就是最大值


代码:

public int findLength(int[] A, int[] B) {
        if(A == null && B == null)
            return 0;
        int [][] dp = new int [A.length + 1][B.length + 1];
        int max = 0;
        for(int i=1;i<=A.length;i++){
            for(int j=1;j<=B.length;j++){
                if(i-1 == 0 || j-1 == 0){
                    dp[i][j] = 0;
                }
                if(A[i-1] == B[j-1]){
                    dp[i][j] = dp[i-1][j-1] + 1;
                    max = Math.max(max, dp[i][j]);
                }
            }
        }
        return max;
}
上一篇 下一篇

猜你喜欢

热点阅读