forked from hijiangtao/LeetCode-with-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathres.js
36 lines (33 loc) · 735 Bytes
/
res.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
/**
* KMP
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function(haystack, needle) {
const hlen = haystack.length;
const nlen = needle.length;
if (!nlen) return 0;
if (!hlen) return -1;
let FSM = new Array(nlen);
let X = 0, match = 0;
for (let i = 0; i < nlen; i++) {
match = needle[i].charCodeAt();
FSM[i] = new Array(256);
for (let j = 0; j < 256; j++) {
FSM[i][j] = FSM[X][j] || 0;
}
FSM[i][match] = i + 1;
if (i > 0) {
X = FSM[X][match];
}
}
let state = 0;
for (let i = 0; i < hlen; i++) {
state = FSM[state][haystack[i].charCodeAt()];
if (state === nlen) {
return i - nlen + 1;
}
}
return -1;
};