Skip to content

Instantly share code, notes, and snippets.

@Star-Lord-XIII
Last active September 20, 2015 17:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Star-Lord-XIII/3057cf2d7351b915d7b3 to your computer and use it in GitHub Desktop.
Save Star-Lord-XIII/3057cf2d7351b915d7b3 to your computer and use it in GitHub Desktop.
Knuth–Morris–Pratt algorithm's javascript implementation in 123 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