Leetcode 718 - Maximum Length of Repeated Subarray

题目:

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]:str1中前i-1个字符和str2中前j-1个字符中子字符串最大的共同字符串的长度。
  • str1中第i个字符和str2中第j个字符相等的时候。

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;
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容