Skip to content

Instantly share code, notes, and snippets.

@Hanaasagi
Created June 25, 2017 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hanaasagi/3e8063604e707635f3f9fa742c244c26 to your computer and use it in GitHub Desktop.
Save Hanaasagi/3e8063604e707635f3f9fa742c244c26 to your computer and use it in GitHub Desktop.
最长子串 可以使用 difflib
def longest_substring(str1, str2):
"""
>>> longest_substring("apple pie available", "apple pies")
'apple pie'
>>> longest_substring("apples", "appleses")
'apples'
>>> longest_substring("bapples", "cappleses")
'apples'
"""
result = ""
len1, len2 = len(str1), len(str2)
for i in range(len1):
match = ""
for j in range(len2):
if (i + j < len1 and str1[i + j] == str2[j]):
match += str2[j]
else:
if (len(match) > len(result)):
result = match
match = ""
return result
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment