Skip to content

Instantly share code, notes, and snippets.

@bicepjai
Created April 8, 2012 06:25
Show Gist options
  • Select an option

  • Save bicepjai/2335203 to your computer and use it in GitHub Desktop.

Select an option

Save bicepjai/2335203 to your computer and use it in GitHub Desktop.
knuth morris pratt algorithm
#! /usr/bin/env python
# Description: Knuth-Morris-Pratt algorithm
__author__ = 'Jay <bicepjai@gmail.com>'
def prefix_table(p):
m = len(p)
pi = [0] * m
k = 0
for q in range(1, m):
while k > 0 and p[k] != p[q]:
k = pi[k - 1]
if p[k] == p[q]:
k = k + 1
pi[q] = k
return pi
def kmp_matcher(t, p):
n = len(t)
m = len(p)
pi = prefix_table(p)
q = 0
for i in range(n):
while q > 0 and p[q] != t[i]:
q = pi[q - 1]
if p[q] == t[i]:
q = q + 1
if q == m:
return i - m + 1
return -1
@zwhitchcox
Copy link
Copy Markdown

I don't supposed you could modify this slightly to show each instance, and not just one, could you?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment