Created
October 16, 2018 11:21
-
-
Save geekf/7c3fb63ece8884244b8f441da0009a68 to your computer and use it in GitHub Desktop.
Sample implementation for KMP Match 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
function computeLpsArray(pat) { | |
let len = 0; | |
let i = 1; | |
const lps = []; | |
lps[0] = 0; | |
while (i < pat.length) { | |
if (pat.charAt(i) === pat.charAt(len)) { | |
len++; | |
lps[i] = len; | |
i++; | |
} else { | |
if (len != 0) { | |
len = lps[len - 1]; | |
} else { | |
lps[i] = len; | |
i++; | |
} | |
} | |
} | |
return lps; | |
} | |
function kmpMatch(pat, txt) { | |
const lps = computeLpsArray(pat); | |
let i = 0; | |
let j = 0; | |
while (i < txt.length) { | |
if (pat.charAt(j) === txt.charAt(i)) { | |
i++; | |
j++; | |
} | |
if (j === pat.length) { | |
console.log("Found pattern at index " + (i -j)); | |
j = lps[j - 1]; | |
} else if (i < txt.length && pat.charAt(j) !== txt.charAt(i)) { | |
if (j !== 0) { | |
j = lps[j - 1]; | |
} else { | |
i++; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment