Skip to content

Instantly share code, notes, and snippets.

@shuson
Created October 29, 2014 08:16
Show Gist options
  • Save shuson/a246e99076de5c295cf3 to your computer and use it in GitHub Desktop.
Save shuson/a246e99076de5c295cf3 to your computer and use it in GitHub Desktop.
The KMP Algorithm implementation in Python
def buildPMT(s):
"""
PartialMatchTable of string s
"""
prefix = [s[:i+1] for i in range(len(s)-1)]
postfix = [s[i+1:] for i in range(len(s)-1)]
intersection = list(set(prefix) & set(postfix))
if intersection:
return len(intersection[0])
return 0
def kmp(src,target):
i = 0
while i < len(src) - len(target) + 1:
match = True
for j in xrange(len(target)):
if src[i+j] != target[j]:
match = False
break
if match:
return True
# j is the unmatched postion in target
if j:
i += j - buildPMT(target[:j]) #move to the postion by i and compared string's length of target
else:
i += 1
return False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment