Skip to content

Instantly share code, notes, and snippets.

@PulkitAgg
Created July 17, 2021 06:30
Show Gist options
  • Save PulkitAgg/b709efcd86e10441bfc378533c59ede5 to your computer and use it in GitHub Desktop.
Save PulkitAgg/b709efcd86e10441bfc378533c59ede5 to your computer and use it in GitHub Desktop.
KMP (Knuth-Morris-Pratt) String matching program
Reference: https://www.youtube.com/watch?v=4jY57Ehc14Y
// JS implementation
function KMP(arr, pat) {
let arrLen = arr.length;
let patLen = pat.length;
let i=0, j=0;
let lps = computeLPS(pat);
while(i < (arrLen - patLen +1 )) {
if(arr[i] == pat[j]) {
i++;
j++;
} else {
if(j != 0 ) {
j = lps[j-1];
} else {
i++;
}
}
if(j == patLen) {
console.log("occurrence at", i - j);
j = lps[j-1];
}
}
}
function computeLPS(pat) {
let patLen = pat.length;
let len = 0, i = 1;
let lps = new Array(patLen).fill(0);
while (i < patLen) {
if(pat[i] == pat[len]) {
lps[i] = len + 1;
len++;
i++;
} else {
if(len != 0) {
len = lps[len-1];
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment