最长公共子序列
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
n = len(text1)
m = len(text2)
dp = [[0]*(m+1)for _ in range(n+1)]
# print(dp)
for i in range(1,n+1):
for j in range(1,m+1):
t1 = 0
if text1[i-1]==text2[j-1] : # text当前位置要比i、j少1, 都参与匹配。
t1 = dp[i-1][j-1] + 1
t2 = max(dp[i-1][j], dp[i][j-1]) # 最多一个参与匹配。
dp[i][j] = max(t1,t2)
# print(dp)
return dp[n][m]
最长公共子串
子串要求连续,子序列这没有这个要求,子串要记录最长子串的位置和长度
动态规划的逻辑:
遍历,求以(i, j)字母结尾子串的`公共子串`长度,
如果s1[i][j] != s2[i][j] , 则dp[i+1][j+1] =0, 如果相等则求出当前的长度,并更新最大长度mmax
# copy from internet
def find_lcsubstr(s1, s2):
m=[[0 for i in range(len(s2)+1)] for j in range(len(s1)+1)] #生成0矩阵,为方便后续计算,比字符串长度多了一列
mmax=0 #最长匹配的长度
p=0 #最长匹配对应在s1中的最后一位
for i in range(len(s1)):
for j in range(len(s2)):
if s1[i]==s2[j]:
m[i+1][j+1]=m[i][j]+1
if m[i+1][j+1]>mmax:
mmax=m[i+1][j+1]
p=i+1
return s1[p-mmax:p],mmax #返回最长子串及其长度
print(find_lcsubstr('abcdfg','abdfg'))