Skip to content

Commit d7d00a1

Browse files
authored
Update 28-implement-strStr().js
1 parent e9909d1 commit d7d00a1

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

28-implement-strStr().js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,44 @@
1+
/**
2+
* @param {string} haystack
3+
* @param {string} needle
4+
* @return {number}
5+
*/
6+
const strStr = function(haystack, needle) {
7+
const m = haystack.length, n = needle.length
8+
9+
const lps = process(needle)
10+
for(let j = 0, i = 0; i < m; i++) {
11+
while(j > 0 && haystack[i] !== needle[j]) {
12+
j = lps[j - 1]
13+
}
14+
if(haystack[i] === needle[j]) {
15+
j++
16+
if(j === n) {
17+
return i - n + 1
18+
}
19+
}
20+
}
21+
return -1
22+
23+
function process(s) {
24+
const n = s.length
25+
const lps = Array(n).fill(0)
26+
for(let len = 0, i = 1; i < n; i++) {
27+
while(len > 0 && s[i] !== s[len]) {
28+
len = lps[len - 1]
29+
}
30+
if(s[i] === s[len]) {
31+
len++
32+
lps[i] = len
33+
}
34+
}
35+
36+
return lps
37+
}
38+
};
39+
40+
// another
41+
142
/**
243
* @param {string} haystack
344
* @param {string} needle

0 commit comments

Comments
 (0)