地址:https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray/
描述:
给两个整数数组 nums1 和 nums2 ,返回两个数组中公共的 、长度最长的子数组的长度 。
实例1:
输入:nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
输出:3
解释:长度最长的公共子数组是 [3,2,1] 。
实例2:
输入:nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
输出:5
思路:
答案:
class Solution {
public int findLength(int[] nums1, int[] nums2) {
int length1 = nums1.length;
int length2 = nums2.length;
int[][] dp = new int[length1 + 1][length2 + 2];
int res = 0;
for (int i = 1; i <= length1; i++) {
for (int j = 1; j <= length2; j++) {
if (nums1[i - 1] == nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
res = Math.max(res, dp[i][j]);
}
}
}
return res;
}
}