![image-20210604124658458](https://img-blog.csdnimg.cn/img_convert/6392abf7cd8c7e19f76ef9069bdf464f.png)
优秀解法:滑动窗口
![错开比较.gif](https://img-blog.csdnimg.cn/img_convert/fd92efec67fe5fa9625e3730c7f0754e.gif)
class Solution {
public int findLength(int[] nums1, int[] nums2) {
return nums1.length < nums2.length ? changeList(nums1,nums2) : changeList(nums2,nums1);
}
public int changeList(int[] nums1,int[] nums2){
int res = 0;
int an = nums1.length,bn = nums2.length;
for(int i = an; i > 0; i--)
res = Math.max(res,getMaxLength(nums1,0,nums2,bn - i,i));
for(int j = 0; j <= bn - an; j++)
res = Math.max(res,getMaxLength(nums1,0,nums2,j,an));
for(int k = 0; k < an; k++)
res = Math.max(res,getMaxLength(nums1,k,nums2,0,an - k));
return res;
}
public int getMaxLength(int[] nums1,int one,int[] nums2,int two,int len){
int count = 0,max = 0;
for(int i = 0; i < len; i++){
if(nums1[one + i] == nums2[two + i]){
count++;
}else if(count > 0){
max = Math.max(max,count);
count = 0;
}
}
return Math.max(max,count);
}
}
![image-20210604124801800](https://img-blog.csdnimg.cn/img_convert/33bfe9c11d579ba041656a1fd26f3783.png)
参考答案