题目
题解
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
# 定义状态:dp[i][j]表示s1[0:i]和s2[0:j]的最长公共子序列
dp = [[0 for j in range(len(text2)+1)] for i in range(len(text1) + 1)]
# badcase: dp[i][0] = 0, dp[0][j] = 0
# 状态转移
for i in range(1, len(text1) + 1):
for j in range(1, len(text2) + 1):
# 若相等,则这个字符一定在LCS中
if text1[i-1] == text2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
# 否则至少有一个字符不在LCS中(*)
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[len(text1)][len(text2)]