Last active
April 10, 2022 10:05
-
-
Save uztbt/60c22e4212d462ee1e62020c3dca18a0 to your computer and use it in GitHub Desktop.
Visit https://yuji.page/kmp-algorithm/ for more information.
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
export function KMPsearch(s: string, w: string): number[] { | |
const acc: number[] = []; | |
const LPS: number[] = createLPSArray(w); | |
let [i, j] = [0, 0]; | |
while (i < s.length) { | |
if (s[i] === w[j]) { | |
i += 1; | |
j += 1; | |
if(j === w.length) { | |
acc.push(i-j); | |
j = LPS[j-1]; | |
} | |
} else { | |
if (j === 0) i += 1; | |
else j = LPS[j-1] | |
} | |
} | |
return acc; | |
} | |
function createLPSArray(w: string): number[] { | |
const lps: number[] = [0]; | |
let len = 0; // The last item of lps. | |
let i = 1; | |
while (i < w.length) { | |
if (w.charAt(i) === w.charAt(len)) { | |
lps.push(++len); | |
i++; | |
} else { | |
if (len !== 0) len = lps[len-1]; // Refer to the proof! | |
else lps[i++] = 0; | |
} | |
} | |
return lps; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment