3 回答

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
它稱為最長(zhǎng)公共子串問(wèn)題。在這里,我提出了一個(gè)簡(jiǎn)單,易于理解但效率低下的解決方案。為大型字符串生成正確的輸出將花費(fèi)很長(zhǎng)時(shí)間,因?yàn)樵撍惴ǖ膹?fù)雜度為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")
產(chǎn)量
apple pie
apples
apples

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
為了完整起見(jiàn),difflib在標(biāo)準(zhǔn)庫(kù)中提供了許多序列比較實(shí)用程序。例如find_longest_match,當(dāng)在字符串上使用時(shí),它會(huì)找到最長(zhǎng)的公共子字符串。使用示例:
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
添加回答
舉報(bào)