Created
February 18, 2019 03:44
-
-
Save nodew/20d7da4966c15284a3ae92657158f5a4 to your computer and use it in GitHub Desktop.
Knuth-Morris-Pratt string matcher in TypeScript
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 KMPSearch(pattern: string, text: string): number { | |
if (pattern.length === 0) return 0; | |
const lsp = generateLSP(pattern); | |
let j = 0; | |
for (let i = 0; i < text.length; i++) { | |
while (j > 0 && text.charAt(i) !== pattern.charAt(j)) { | |
j = lsp[j - 1]; | |
} | |
if (text.charAt(i) === pattern.charAt(j)) { | |
j++; | |
if (j === pattern.length) { | |
return i - (j - 1); | |
} | |
} | |
} | |
return -1; | |
} | |
function generateLSP(pattern: string): number[] { | |
if (pattern.length === 0) return []; | |
let lsp: Array<number> = [0]; | |
for (let i = 1; i < pattern.length; i++) { | |
let c = pattern.charAt(i); | |
let j: number = lsp[i - 1]; | |
while (j > 0 && c !== pattern.charAt(j)) { | |
j = lsp[j - 1]; | |
} | |
if (c === pattern.charAt(j)) { | |
j++; | |
} | |
lsp.push(j); | |
} | |
console.log(lsp); | |
return lsp; | |
} | |
console.log(KMPSearch("abcdaba", "abcccccdababcdaba")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment