3 回答

TA貢獻1824條經驗 獲得超6個贊
它稱為最長公共子串問題。在這里,我提出了一個簡單,易于理解但效率低下的解決方案。為大型字符串生成正確的輸出將花費很長時間,因為該算法的復雜度為O(N ^ 2)。
def longestSubstringFinder(string1, string2):
answer = ""
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
print longestSubstringFinder("apple pie available", "apple pies")
print longestSubstringFinder("apples", "appleses")
print longestSubstringFinder("bapples", "cappleses")
產量
apple pie
apples
apples

TA貢獻1865條經驗 獲得超7個贊
為了完整起見,difflib在標準庫中提供了許多序列比較實用程序。例如find_longest_match,當在字符串上使用時,它會找到最長的公共子字符串。使用示例:
from difflib import SequenceMatcher
string1 = "apple pie available"
string2 = "come have some apple pies"
match = SequenceMatcher(None, string1, string2).find_longest_match(0, len(string1), 0, len(string2))
print(match) # -> Match(a=0, b=15, size=9)
print(string1[match.a: match.a + match.size]) # -> apple pie
print(string2[match.b: match.b + match.size]) # -> apple pie
添加回答
舉報