LeetCode.718 Maximum Length of Repeated Subarray(经典DP问题)

来源:互联网 发布:mysql 状态 编辑:程序博客网 时间:2024/05/29 17:06

题目:

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: 3Explanation: 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

分析L:

class Solution {    public int findLength(int[] A, int[] B) {        //给定两个数组,找出两者公共的最长子串        //要求:两个子串的长度均小于1000,元素的范围0-99                //参考:动态规划问题DP,采用一个长度为m+1的一维数组来记录各个位置最长匹配的长度        int n=A.length,m=B.length;        int [] dp=new int[m+1];        int max=0;        for(int i=1;i<=n;i++){            for(int j=m;j>0;j--){                if(A[i-1]==B[j-1]){                    //存在相同的,更新动态数组                    dp[j]=dp[j-1]+1;                    max=Math.max(max,dp[j]);                }else{                    //不存在相同,置0                    dp[j]=0;                }            }        }        return max;            }}


原创粉丝点击