-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmp.js
38 lines (35 loc) · 885 Bytes
/
kmp.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
if (needle.length ===0) return 0;
const getnext = (needle) =>{
let j = 0;
let next = [];
next.push(j);
for(i=1;i<needle.length;++i){
while(j>0&&needle[i]!==needle[j]){
j = next[j-1];
}
if(needle[i]===needle[j]){
j++;
}
next.push(j);
}
return next;
}
let next = getnext(needle);
let j = 0;
for (let i = 0; i < haystack.length; ++i) {
while (j > 0 && haystack[i] !== needle[j])
j = next[j - 1];
if (haystack[i] === needle[j])
j++;
if (j === needle.length)
return (i - needle.length + 1);
}
return -1
};
strStr("sadbutsad","sad")