
function kmp( S , T ) {
let res = 0;
let next = new Array(S.length).fill(0);
getNextIndex(S, next);
let j=0;
for(let i = 0;i < T.length;i++)
{
while(j > 0 && T[i] != S[j])
j = next[j - 1];
if(T[i] == S[j])
j++;
if(j == S.length)
{
res++;
j = next[j - 1];
}
}
return res;
}
function getNextIndex(S, next) {
let j = 0;
for(let i = 1; i< S.length; i++) {
while(j > 0 && S[i] != S[j])
j = next[j - 1];
if( S[i] == S[j] ) {
j++;
}
next[i] = j;
}
}
module.exports = {
kmp : kmp
};
kmp算法_牛客题霸_牛客网 (nowcoder.com)