Created
June 25, 2017 07:43
-
-
Save Hanaasagi/3e8063604e707635f3f9fa742c244c26 to your computer and use it in GitHub Desktop.
最长子串 可以使用 difflib
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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