题目描述: 最长重复子数组
给两个整数数组 A
和 B
,返回两个数组中公共的、长度最长的子数组的长度。
示例 1:
输入: A: [1,0,0,1,1] B: [1,0,0,0,1] 输出: 3 解释: 长度最长的公共子数组是 [1,0,0] or [0,0,1]。
说明:
- 1 <= len(A), len(B) <= 1000
- 0 <= A[i], B[i] < 100
引申概念:
最长公共子序列:
最长公共子串:
python代码:
最长公共子串:
1 def findLength( A, B): 2 n = len(A) 3 m = len(B) 4 dis = [[0 for i in range(n + 1)] for j in range(m + 1)] 5 for i in range(m): 6 for j in range(n): 7 if A[i] == B[j]: 8 dis[i + 1][j + 1] = dis[i][j] + 1 9 max = 0 10 for i in range(n+1): 11 for j in range(n+1): 12 if dis[i][j] > max: 13 max = dis[i][j] 14 15 return max 16 17 if __name__ == "__main__": 18 19 A = [1, 0, 0, 1, 1] 20 B = [1, 0, 0, 0, 1] 21 print(findLength(A,B))
输出结果:3 此时最长公共子串为[1,0,0] 或者【0,0,1】
1 | 0 | 0 | 0 | 1 | ||
0 | 0 | 0 | 0 | 0 | 0 | |
1 | 0 | 1 | 0 | 0 | 0 | 1 |
0 | 0 | 0 | 2 | 1 | 1 | 0 |
0 | 0 | 0 | 1 | 3 | 2 | 0 |
1 | 0 | 1 | 0 | 0 | 0 | 3 |
1 | 0 | 1 | 0 | 0 | 0 | 1 |
最长公共子序列:
1 def findLength( A, B): 2 n = len(A) 3 m = len(B) 4 dis = [[0 for i in range(n + 1)] for j in range(m + 1)] 5 for i in range(m): 6 for j in range(n): 7 if A[i] == B[j]: 8 dis[i + 1][j + 1] = dis[i][j] + 1 9 else: 10 dis[i + 1][j + 1] = max(dis[i+1][j],dis[i][j+1]) 11 12 return dis[-1][-1] 13 14 if __name__ == "__main__": 15 16 A = [1, 0, 0, 1, 1] 17 B = [1, 0, 0, 0, 1] 18 print(findLength(A,B))
输出结果:4 此时最长公共子序列为[1,0,0,1]
1 | 0 | 0 | 0 | 1 | ||
0 | 0 | 0 | 0 | 0 | 0 | |
1 | 0 | 1 | 1 | 1 | 1 | 1 |
0 | 0 | 1 | 2 | 2 | 2 | 2 |
0 | 0 | 1 | 2 | 3 | 3 | 3 |
1 | 0 | 1 | 2 | 3 | 3 | 4 |
1 | 0 | 1 | 2 | 3 | 3 | 4 |
定义来源:https://blog.csdn.net/ggdhs/article/details/90713154
题目来源:https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray/