这里是Python初学者,我正在尝试制作一个程序,从输入中输出两个字符串中最长的公共子字符串
例如:
word1 = input('Give 1. word: xlaqseabcitt')
word2 = input('Give 2. word: peoritabcpeor')
想要的输出:
abc
到目前为止,我有这样的代码:
word1 = input("Give 1. word: ")
word2 = input("Give 2. word: ")
longestSegment = ""
tempSegment = ""
for i in range(len(word1)):
if word1[i] == word2[i]:
tempSegment += word1[i]
else:
tempSegment = ""
if len(tempSegment) > len(longestSegment):
longestSegment = tempSegment
print(longestSegment)
当word2比word1短并且它没有给我公共子字符串时,我最终使用IndexError
有什么建议吗
谢谢你的帮助
编辑:我找到了这个解决方案:
string1 = input('Give 1. word: ')
string2 = input('Give 2. word: ')
answer = ""
len1, len2 = len(string1), len(string2)
for i in range(len1):
for j in range(len2):
lcs_temp=0
match=''
while ((i+lcs_temp < len1) and (j+lcs_temp<len2) and string1[i+lcs_temp] == string2[j+lcs_temp]):
match += string2[j+lcs_temp]
lcs_temp+=1
if (len(match) > len(answer)):
answer = match
print(answer)
有没有办法让这段代码更清晰,更适合初学者
您可以从包含每个字符位置的第一个字符串(键入字符)构建字典。然后遍历第二个字符串,并将每个字符的子字符串与该位置的第二个字符串的其余部分进行比较:
相关问题 更多 >
编程相关推荐