Poison

718. Maximum Length of Repeated Subarray

DP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public int findLength(int[] nums1, int[] nums2) {
int m = nums1.length, n = nums2.length;

int maxLength = 0;
// 定义 dp[i][j] 为以 nums1[i - 1] 结尾的子数组与以 nums2[j - 1] 结尾的子数组的最长公共子数组的长度
int[][] dp = new int[m + 1][n + 1];

for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (nums1[i - 1] == nums2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = 0;
}

maxLength = Math.max(maxLength, dp[i][j]);
}
}

return maxLength;
}
}

因为 dp[i][j] 仅依赖 dp[i - 1][j - 1],所以可以降为一维数组:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int findLength(int[] nums1, int[] nums2) {
int[] dp = new int[nums2.length + 1]; // depends on dp[j - 1]
int maxLength = 0;
for (int i = 1; i <= nums1.length; i++) {
for (int j = nums2.length; j >= 1; j--) { // 因为 dp[j] 依赖 dp[j - 1], 所以从右往左遍历
if (nums1[i - 1] == nums2[j - 1]) {
dp[j] = dp[j - 1] + 1;
}

maxLength = Math.max(maxLength, dp[j]);
}
}

return maxLength;
}
}
Sliding Window
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class Solution {
public int findLength(int[] nums1, int[] nums2) {
if (nums2.length < nums1.length) {
return findLength(nums2, nums1);
}

// nums1: 3 4 5
// nums2: 5 6 7 8 9

int maxCommonLength = 0;

// 3 4 5 3 4 5
// 5 6 7 8 9 -> 5 6 7 8 9
for (int i = nums1.length - 1; i >= 0; i--) {
int j = 0;
maxCommonLength = Math.max(maxCommonLength, getMaxCommonLength(nums1, i, nums2, j));
}

// 3 4 5 3 4 5
// 5 6 7 8 9 -> 5 6 7 8 9
for (int j = 1; j <= nums2.length - nums1.length; j++) {
int i = 0;
maxCommonLength = Math.max(maxCommonLength, getMaxCommonLength(nums1, i, nums2, j));
}

// 3 4 5 3 4 5
// 5 6 7 8 9 -> 5 6 7 8 9
for (int j = nums2.length - nums1.length + 1; j < nums2.length; j++) {
int i = 0;
maxCommonLength = Math.max(maxCommonLength, getMaxCommonLength(nums1, i, nums2, j));
}

return maxCommonLength;
}

private int getMaxCommonLength(int[] nums1, int i, int[] nums2, int j) {
int maxCommonLength = 0;
int commonLength = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2[j]) {
commonLength++;
maxCommonLength = Math.max(maxCommonLength, commonLength);
} else {
commonLength = 0;
}
i++;
j++;
}

return maxCommonLength;
}
}
Reference

718. Maximum Length of Repeated Subarray