给定两个字符串,求解这两个字符串的最长公共子序列(Longest Common Sequence)。比如字符串1:BDCABA;字符串2:ABCBDAB
则这两个字符串的最长公共子序列长度为4,最长公共子序列是:BCBA
代码:
def findLCS(A, n, B, m): # write code here record = 0 maxNum = 0 result = [] for i in range(n): for j in range(m): if A[i] == B[j]: if A[i] not in result: record += 1 # print(A[i]) result.append(A[i]) if maxNum < record: maxNum = record return maxNum,"".join(result) if __name__ == "__main__": A = "BDCABA" n = 6 B = "ABCBDAB" m =7 print(findLCS(A, n, B, m))