Skip to content

Instantly share code, notes, and snippets.

@longfin
Created December 10, 2011 18:04
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 longfin/1455788 to your computer and use it in GitHub Desktop.
Save longfin/1455788 to your computer and use it in GitHub Desktop.
kmp search
"""
http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
"""
def kmp_make_table(word):
table = len(word) * [0]
pos = 2
cnd = 0
table[0] = -1
table[1] = 0
while pos < len(word):
if word[pos - 1] == word[cnd]:
cnd += 1
table[pos] = cnd
pos += 1
elif cnd > 0:
cnd = table[cnd]
else:
table[pos] = 0
pos += 1
return table
def kmp_search(text, pattern):
t = kmp_make_table(pattern)
m = 0
i = 0
while m+i < len(text):
if pattern[i] == text[m+i]:
if i == len(pattern) - 1:
return m
i += 1
else:
m = m + i - t[i]
if t[i] > -1:
i = t[i]
else:
i = 0
return -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment