718. Maximum Length of Repeated Subarray

718. Maximum Length of Repeated Subarray

1. 题目
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.
Example 1:
Input:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
Output: 3
Explanation:
The repeated subarray with maximum length is [3, 2, 1].
Note:
1 <= len(A), len(B) <= 1000
0 <= A[i], B[i] < 100

2. 题目分析
找两个数组之间公共的子数组,这个子数组的元素位置是连续的而且相对位置是一样的。比如说A={1,2,3},B={4,3,6,2,1},则A与B没有公共子数组。

3. 解题思路
求最长连续的公共子数组,使用动态规划的思路,
使用一个二维的DP数组,其中dp[i][j]表示数组A的前i个数字和数组B的前j个数字的最长子数组的长度。
当A[i] == B[j]的地方,而且还要加上左上方的dp值,即dp[i-1][j-1],所以当前的dp[i][j]就等于dp[i-1][j-1] + 1,
当A[i] != B[j]时,直接赋值为0,因为子数组是要连续的,一旦不匹配了,就不能再增加长度了。

4. 代码实现(java)

package com.algorithm.leetcode.dynamicAllocation;

/**
 * Created by 凌 on 2019/2/9.
 * 注释:718. Maximum Length of Repeated Subarray
 */
public class FindLength {
    /**
     * 求最长连续的子数组,使用动态规划的思路,
     * 使用一个二维的DP数组,其中dp[i][j]表示数组A的前i个数字和数组B的前j个数字的最长子数组的长度。
     * 当A[i] == B[j]的地方,而且还要加上左上方的dp值,即dp[i-1][j-1],所以当前的dp[i][j]就等于dp[i-1][j-1] + 1,
     * 当A[i] != B[j]时,直接赋值为0,因为子数组是要连续的,一旦不匹配了,就不能再增加长度了。
     * @param A
     * @param B
     * @return
     */
    public int findLength(int[] A, int[] B) {
        if (A == null || B==null){
            return 0;
        }
        int maxCommonLenth = 0;
        int[][] common=new int[A.length][B.length];
        //初始化第一行第一列
        for(int i=0;i<A.length;i++){
            if(B[0]==A[i]){
                common[i][0]=1;
            }
        }
        for(int i=0;i<B.length;i++){
            if(B[i]==A[0]){
                common[0][i]=1;
            }
        }
        for (int i = 1; i < A.length; i++) {
            for (int j = 1; j < B.length; j++) {
                if (A[i] == B[j]){
                    common[i][j] = common[i-1][j-1]+1;
                    maxCommonLenth = Math.max(maxCommonLenth,common[i][j]);
                }
            }
        }
        return maxCommonLenth;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值