Created
April 8, 2012 06:25
-
-
Save bicepjai/2335203 to your computer and use it in GitHub Desktop.
knuth morris pratt algorithm
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
#! /usr/bin/env python | |
# Description: Knuth-Morris-Pratt algorithm | |
__author__ = 'Jay <[email protected]>' | |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't supposed you could modify this slightly to show each instance, and not just one, could you?