我的作业问题之一是找到两个弦的最长的公共子序列。我的代码正常工作,但是花了太长时间。
我知道我需要使用记忆来帮助事情更快地运行,但是我不太确定如何解决这个问题?注意:我不愿意在代码中使用循环或导入:
def longest_common_substring(s1, s2):
""" finds the longest common subsequence of two strings """
final = ''
if s1[0] == s2[0]:
final += (s1[0])
if len(s1) > 1 and len(s2) > 1:
final += (longest_common_substring(s1[1:], s2[1:]))
else:
if len(s1) > 1 and len(s2) > 1:
left = longest_common_substring(s1[1:], s2)
right = longest_common_substring(s1, s2[1:])
if len(left) > len(right):
final += left
else:
final += right
elif len(s1) == 1 and len(s2) > 1:
final += longest_common_substring(s1, s2[1:])
elif len(s2) == 1 and len(s1) > 1:
final += longest_common_substring(s1[1:], s2)
return final
例如
s1 = "Look at me, I can fly!"
s2 =“看看那是一只苍蝇” 打印(longest_common_substring(s1,s2))
应提供
"Look at , a fly"