Last active
September 20, 2015 17:27
-
-
Save Star-Lord-XIII/3057cf2d7351b915d7b3 to your computer and use it in GitHub Desktop.
Knuth–Morris–Pratt algorithm's javascript implementation in 123 characters.
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
p = "AABA" // pattern | |
t = "AABAACAADAABAAABAA" // text | |
m = p.length | |
n = t.length; | |
L = [];x=m;while(x--)L.push(0) // LPS array of size m, initialized to 0 | |
e = []; // array to store ending indices of the pattern-match in the text | |
// Knuth–Morris–Pratt algorithm | |
for(i=1,l=0;i<m;)p[i]==p[l]?L[i++]=++l:l>0?l=L[l-1]:++i;for(i=j=0;i<n;++i)p[j]==t[i]?++j==m?e.push(i):0:j>0&&i--?j=L[j-1]:0 | |
// Print starting positions of pattern-matches in text | |
for(i=0;i<e.length;++i) | |
console.log(e[i]+1-m) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment