Created
November 24, 2011 03:39
-
-
Save andykant/1390579 to your computer and use it in GitHub Desktop.
CoffeeScript implementation of the Knuth–Morris–Pratt (KMP) 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
# http://en.wikipedia.org/wiki/KMP_algorithm | |
kmp_tables = {} | |
kmp_search = (haystack, needle) -> | |
# compute/cache the lookup table for this needle | |
lookup = kmp_tables[needle] = kmp_tables[needle] || (-> | |
[pos, sub, table] = [2, 0, [-1, 0]] | |
while pos < needle.length | |
if needle[pos-1] == needle[sub] | |
sub++ | |
table[pos] = sub | |
pos++ | |
else if sub > 0 | |
sub = table[sub] | |
else | |
table[pos] = 0 | |
pos++ | |
return table | |
)() | |
# search for the needle in the haystack | |
[match, index] = [0, 0] | |
while match+index < haystack.length | |
if needle[index] == haystack[match+index] | |
return match if index == needle.length - 1 | |
index++ | |
else | |
match = match + index - lookup[index] | |
index = if lookup[index] > -1 then lookup[index] else 0 | |
return -1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment