Skip to content

Commit 105a8dc

Browse files
authored
Update 28-implement-strStr().js
1 parent 7e0fea9 commit 105a8dc

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

28-implement-strStr().js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,35 @@
1+
/**
2+
* @param {string} haystack
3+
* @param {string} needle
4+
* @return {number}
5+
*/
6+
const strStr = function(a, b) {
7+
if(b === '') return 0
8+
if(a.length < b.length) return -1
9+
if(a.length === b.length) return a === b ? 0 : -1
10+
const m = a.length, n = b.length
11+
const fail = Array(n).fill(-1)
12+
// DFA
13+
for(let i = 1; i < n; i++) {
14+
let j = fail[i - 1]
15+
while(j !== -1 && b[j + 1] !== b[i]) {
16+
j = fail[j]
17+
}
18+
if(b[j + 1] === b[i]) fail[i] = j + 1
19+
}
20+
let pos = -1
21+
for(let i = 0; i < m; i++) {
22+
while(pos !== -1 && a[i] !== b[pos + 1]) pos = fail[pos]
23+
if(a[i] === b[pos + 1]) {
24+
pos++
25+
if(pos === n - 1) return i - n + 1
26+
}
27+
}
28+
return -1
29+
};
30+
31+
// another
32+
133
/**
234
* @param {string} haystack
335
* @param {string} needle

0 commit comments

Comments
 (0)