Last active
December 19, 2019 15:31
-
-
Save gkucmierz/4c3b41ec0b403f4b3821973bcf780018 to your computer and use it in GitHub Desktop.
count all substring occurrences
This file contains hidden or 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
const KMPSearch = (() => { | |
const computeLPSArray = pat => { | |
let len = 0; | |
let i = 1; | |
const lps = [0]; | |
while (i < pat.length) { | |
if (pat[i] === pat[len]) { | |
++len; | |
lps[i] = len; | |
++i; | |
} else { | |
if (len !== 0) { | |
len = lps[len - 1]; | |
} else { | |
lps[i] = len; | |
++i; | |
} | |
} | |
} | |
return lps; | |
}; | |
return (pat, txt) => { | |
const [m, n] = [pat.length, txt.length]; | |
let [i, j, res] = [0, 0, 0]; | |
const lps = computeLPSArray(pat); | |
while (i < n) { | |
if (pat[j] === txt[i]) { | |
++j; | |
++i; | |
} | |
if (j === m) { | |
j = lps[j - 1]; | |
++res; | |
} else if (i < n && pat[j] !== txt[i]) { | |
if (j !== 0) { | |
j = lps[j - 1]; | |
} else { | |
++i; | |
} | |
} | |
} | |
return res; | |
}; | |
})(); | |
const txt = "110100010101011"; | |
const pat = "1010"; | |
KMPSearch(pat, txt); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment