Maximum Length of Repeated Subarray
这个题跟LCS在一定程度上非常相似,不同的在于这里需要连续的子字符串,基于这一点就没有那么多奇奇怪怪的逻辑了,剩下来的只有一个转移方程了
dp[i][j] = dp[i - 1][j - 1] + 1 if A[i] == B[j]
dp[i][j] = 0
另外这里的dp[i][j]代表以A[i]和B[j]结尾的最长公共子串,最后我们必须逐行遍历找最大值,这个最大值不一定是最后一个值
class Solution(object):
def findLength(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: int
"""
n, m = len(A), len(B)
dp = [[0] * (m + 1) for _ in xrange(n + 1)]
for i in xrange(1, n + 1):
for j in xrange(1, m + 1):
if A[i - 1] == B[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
return max(max(num) for num in dp)