动态规划(空间优化):
def LCS(a, b):
""" 最长公共子序列 空间复杂度为O(min(a,b))+1 记录左上角值"""
if len(a) < len(b):
a, b = b, a
print(a, b)
list = [0 for i in range(len(b))]
for i in range(len(a)):
upperleft = 0
for j in range(len(b)):
if a[i] == b[j]:
upperleft, list[j] = list[j], upperleft+1
# 记住修改之前list[j]的值,为了下次作为左上角的值使用
else:
upperleft = list[j]
# 记住修改之前list[j]的值,为了下次作为左上角的值使用
list[j] = (max(list[j], list[j-1]) if j != 0 else list[j])
print(list)
return list[-1]
def main():
# a="67824681"
# b="123456789"
a = input("Please input one string:")
print("Your enter is : ", a)
b = input("Please input another string:")
print("Your enter is : ", b)
print("The longth of the longest common subsequence is :", LCS(a, b))
if __name__ == '__main__':
main()