【题目】
两个数组,求他们最长的相同子串长度,数组长度不一定相同
Given two integer arrays nums1
and nums2
, return the maximum length of a subarray that appears in both arrays.
Example 1:
Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7] Output: 3 Explanation: The repeated subarray with maximum length is [3,2,1].
Example 2:
Input: nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0] Output: 5
【思路】
- b站:https://www.bilibili.com/video/BV1eC4y187NR
-
想象成nums1和nums2横纵轴,m*n矩阵,对角线相关
【代码】
class Solution { public int findLength(int[] nums1, int[] nums2) { int ans=0; int[][] dp=new int[nums1.length][nums2.length]; for(int i=0;i<nums1.length;i++){ for(int j=0;j<nums2.length;j++){ if(nums1[i]==nums2[j]){ if(i==0||j==0) dp[i][j]=1;//初始化,第N排和第0排比较,第N列和第0列比较 else dp[i][j]=dp[i-1][j-1]+1; ans=Math.max(ans,dp[i][j]);//只在有重合时,才判断是否比之前大 } } } return ans; } }