Created
November 16, 2020 03:05
-
-
Save Qquanwei/fc34cab9319d321de9d62d044f2e1f06 to your computer and use it in GitHub Desktop.
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 getMaxPrefixAndSuffix(P) { | |
let i = 0; | |
let len = 0; | |
for (let i = P.length - 1; i >= 0; --i) { | |
if (P.slice(0, i) === P.slice(-i)) { | |
return i; | |
} | |
} | |
return 0; | |
} | |
function computeX(pattern) { | |
let x = [0]; | |
for (let i = 1; i < pattern.length; ++i) { | |
x.push(getMaxPrefixAndSuffix(pattern.slice(0, i + 1))); | |
} | |
return x; | |
} | |
function kmpsearch(str, pattern) { | |
const x = computeX(pattern); | |
let k = 0; | |
let s = 0; | |
while (k < pattern.length && s <(str.length - pattern.length)) { | |
if (str[s + k] === pattern[k]) { | |
k++; | |
if (k === pattern.length) { | |
return s; | |
} | |
} else { | |
k = x[Math.max(k-1, 0)]; | |
s = s + Math.max(k, 1); | |
} | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment