Skip to content

Instantly share code, notes, and snippets.

@girish3
Created February 14, 2017 17:46
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 girish3/435967f9ec076ba78fe7605f45c48bb5 to your computer and use it in GitHub Desktop.
Save girish3/435967f9ec076ba78fe7605f45c48bb5 to your computer and use it in GitHub Desktop.
W = "acabacacd"
T = "acfacabacabacacdk"
# this method is from above code snippet.
aux = creatAux(W)
# counter for word W
i = 0
# counter for text T
j = 0
while j < len(T):
# We need to handle 2 conditions when there is a mismatch
if W[i] != T[j]:
# 1st condition
if i == 0:
# starting again from the next character in the text T
j += 1
else:
# aux[i-1] will tell from where to compare next
# and no need to match for W[0..aux[i-1] - 1],
# they will match anyway, that’s what kmp is about.
i = aux[i-1]
else:
i += 1
j += 1
# we found the pattern
if i == len(W):
# printing the index
print "found pattern at " + str(j - i)
# if we want to find more patterns, we can
# continue as if no match was found at this point.
i = aux[i-1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment