两个字符串的最长公共子字符串

2024-05-16 12:01:54 发布

您现在位置:Python中文网/ 问答频道 /正文

这里是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)

有没有办法让这段代码更清晰,更适合初学者


Tags: 字符串answerforinputlenmatchtempword
1条回答
网友
1楼 · 发布于 2024-05-16 12:01:54

您可以从包含每个字符位置的第一个字符串(键入字符)构建字典。然后遍历第二个字符串,并将每个字符的子字符串与该位置的第二个字符串的其余部分进行比较:

# extract common prefix
def common(A,B) :
    firstDiff = (i for i,(a,b) in enumerate(zip(A,B)) if a!=b) # 1st difference
    commonLen = next(firstDiff,min(len(A),len(B)))             # common length
    return A[:commonLen]

word1 = "xlaqseabcitt"
word2 = "peoritabcpeor"

# position(s) of each character in word1
sub1 = dict()  
for i,c in enumerate(word1): sub1.setdefault(c,[]).append(i)

# maximum (by length) of common prefixes from matching first characters
maxSub = max((common(word2[i:],word1[j:]) 
                       for i,c in enumerate(word2) 
                                 for j in sub1.get(c,[])),key=len)


print(maxSub) # abc

相关问题 更多 >