难度:media
说明:
给出两个数组,求出两个数组中相同最长子串长度。
题目连接:https://leetcode.com/problems/maximum-length-of-repeated-subarray/
输入范围:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 100
输入案例:
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
首先要注意是子串,也就是连续的元素组成的序列,这个用个二维数组去做吧,然后想快一点就再将其中一个数组每一个元素重复的索引记录到一个链表里面,然后进行遍历即可。
Java:
class Solution { public int findLength(int[] nums1, int[] nums2) { int max = 0, index = 0, pre = 0; int[] begin = new int[101], end = new int[101], next = new int[nums2.length]; for(int i = 0, len = nums2.length; i < len; i ++) { // 想快一点就记录索引 if(begin[nums2[i]] == 0) { begin[nums2[i]] = end[nums2[i]] = i + 1; } else { next[end[nums2[i]] - 1] = i + 1; end[nums2[i]] = i + 1; } } int dp[][] = new int[nums1.length][nums2.length]; for(int i = 0, len1 = nums1.length; i < len1; i ++, pre = 0) for(int j = begin[nums1[i]] - 1; j != -1; j = next[j] - 1) { dp[i][j] = i - 1 >= 0 && j - 1 >= 0 ? dp[i - 1][j - 1] + 1 : 1; max = Math.max(max, dp[i][j]); } return max; } }
C++: