-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.js
38 lines (34 loc) · 841 Bytes
/
solution.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 === '') return 0
let next = [],
i = j = 0
while (i < needle.length) {
if (i === 0 || (needle[i] !== needle[j] && j === 0)) {
next.push(0)
} else if (needle[i] === needle[j]) {
next.push(j + 1)
j++
} else if (needle[i] !== needle[j]) {
j = next[j - 1]
continue
}
i++
}
i = j = 0
while (i < haystack.length && j < needle.length) {
if (haystack[i] == needle[j]) {
i++
j++
} else if (j === 0) {
i++
} else {
j = next[j - 1]
}
}
return j === needle.length ? i - j : -1
};