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;
}
}