LCS
def LCS(A, B):
n = len(A)
m = len(B)
#dp[i][j] 代表 A的前 i 个字符 与 B的前 j 个字符最长公共子序列长度
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
if A[i - 1] == B[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
lcs_max_len = dp[n][m]
lcs = []
i, j = n, m
while i > 0 and j > 0:
if A[i - 1] == B[j - 1]:
lcs.append(A[i - 1])
j -= 1
i -= 1
elif dp[i - 1][j] > dp[i][j - 1]:
i -= 1
else:
j -= 1
lcs.reverse()
return lcs_max_len, lcs
A = input()
B = input()
lcs_len, lcs = LCS(A, B)
print(''.join(lcs))
评论
发表评论