参考了查找两个字符串之间的公共子串
修改了几行并添加了几行。
修改是如果没有找到任何子串,则默认返回答案为“NULL”。
添加了
继续搜索,直到获取到NULL并存储到列表中。
def longestSubstringFinder(string1, string2):
answer = "NULL"
len1, len2 = len(string1), len(string2)
for i in range(len1):
match = ""
for j in range(len2):
if (i + j < len1 and string1[i + j] == string2[j]):
match += string2[j]
else:
if (len(match) > len(answer)): answer = match
match = ""
return answer
mylist = []
def call():
s1 = 'Today is a good day, it is a good idea to have a walk.'
s2 = 'Yesterday was not a good day, but today is good, shall we have a walk?'
s1 = s1.lower()
s2 = s2.lower()
x = longestSubstringFinder(s2,s1)
while(longestSubstringFinder(s2,s1) != "NULL"):
x = longestSubstringFinder(s2,s1)
print(x)
mylist.append(x)
s2 = s2.replace(x,' ')
call()
print ('[%s]' % ','.join(map(str, mylist)))
输出
[ a good day, , have a walk,today is , good]
您的输出结果不同
common = ['today is', 'a good day', 'is', 'a good', 'have a walk']
你对第二个"is"的期望是错误的,因为在s2中只有一个"is"