Created
February 27, 2011 06:49
-
-
Save stevekrenzel/845969 to your computer and use it in GitHub Desktop.
Find the longest common substring between two strings.
This file contains 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
from collections import defaultdict | |
def longest_common_substring(a, b): | |
index = defaultdict(list) | |
for i, c in enumerate(b): | |
index[c].append(i) | |
mxi, mxj, mxsz = 0, 0, 0 | |
matches = defaultdict(int) | |
for i, c in enumerate(a): | |
new_matches = defaultdict(int) | |
for j in index[c]: | |
k = new_matches[j] = matches[j - 1] + 1 | |
if k > mxsz: | |
mxi, mxj, mxsz = i, j, k | |
matches = new_matches | |
return mxi - mxsz + 1, mxj - mxsz + 1, mxsz |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment