leetcode 718( Maximum Length of Repeated Subarray)

来源:互联网 发布:wp10记录仪软件 编辑:程序博客网 时间:2024/06/04 19:16

1.题目描述:给定两个数组,在两个数组中,返回包含相同元素最多的数组的长度。
例子:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
返回:3.
解释:在数组 A和B中最长的子数组为[3,2,1]长度为3.

2.代码:

class Solution{    public int findLength(int [] A, int [] B){    int res = 0;    // java 中 int 默认值为0,需要前一个的值因此长度要比以前的数组大一    int [][] dp = new int[A.length+1][B.length+1];    for(int i = 0; i < A.length; i++){        for(int j = 0; j < B.length; j++){        if(A[i] == B[j]){            dp[i+1][j+1] = dp[i][j] +1;        }        res = Math.max(res, dp[i+1][j+1]);        }    }    return res;    }}
原创粉丝点击