求两个字符串最长公共子序列
时间: 2024-06-14 08:03:55 浏览: 163
以下是求解两个字符串最长公共子序列的方法:
- 使用动态规划算法求解最长公共子序列(Longest Common Subsequence,LCS)。
def longestCommonSubsequence(text1, text2): m, n = len(text1), len(text2) dp = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if text1[i - 1] == text2[j - 1]: dp[i][j] = dp[i - 1][j - 1] + 1 else: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) result = "" i, j = m, n while i > 0 and j > 0: if text1[i - 1] == text2[j - 1]: result = text1[i - 1] + result i -= 1 j -= 1 elif dp[i - 1][j] > dp[i][j - 1]: i -= 1 else: j -= 1 return result text1 = "BDCABA" text2 = "ABCBDAB" print("最长公共子序列:", longestCommonSubsequence(text1, text2)) # 输出:BCAB
相关推荐













