leetcode 718. Python 最长重复子数组
给两个整数数组 A 和 B ,返回两个数组中公共的、长度最长的子数组的长度。
示例 1:
输入:
A: [1,2,3,2,1]
B: [3,2,1,4,7]
输出: 3
解释:
长度最长的公共子数组是 [3, 2, 1]。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
暴力解法
class Solution(object):
def findLength(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
ans = 0
for i in range(len(A)):
for j in range(len(B)):
k = 1
while A[i:i+k] == B[j:j+k] and (i + k) <= len(A) and (i + k) <= len(B):
k += 1
ans = max(ans, k)
return ans - 1
动态规划
class Solution(object):
def findLength(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
dp = [[0]*(len(B)+1) for i in range(len(A)+1)]
for i in range(len(A)-1, -1, -1):
for j in range(len(B)-1, -1, -1):
if A[i] == B[j]:
dp[i][j] = dp[i+1][j+1] + 1
return max(max(row) for row in dp)