如何使用Python找到两个字符串之间的最长公共子串?

Emi*_*i93 9 python

我想编写一个 Python 代码来计算输入中两个字符串之间的最长公共子串。

例子:

word1 = input('Give 1. word: xlaqseabcitt')
word2 = input('Give 2. word: peoritabcpeor')
Run Code Online (Sandbox Code Playgroud)

想要的输出:

abc
Run Code Online (Sandbox Code Playgroud)

到目前为止我有这样的代码:

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)
Run Code Online (Sandbox Code Playgroud)

当 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)
Run Code Online (Sandbox Code Playgroud)

但是,我希望看到一个库函数调用,可用于计算两个字符串之间的最长公共子字符串。

或者,请建议更简洁的代码来实现相同的目的。

Ala*_* T. 3

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

# 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
Run Code Online (Sandbox Code Playgroud)