-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
66 lines (66 loc) · 1.52 KB
/
index.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
var buildPatternTable = function (word) {
let patternTable = [0];
let prefix = 0;
let suffix = 1;
while (suffix < word.length) {
if (word[prefix] === word[suffix]) {
patternTable[suffix] = prefix + 1;
suffix++;
prefix++;
} else if (prefix === 0) {
patternTable[suffix] = 0;
suffix++;
} else {
prefix = patternTable[prefix - 1];
}
}
return patternTable;
};
const patternTable = buildPatternTable(needle);
let i = 0, j = 0;
while (i < haystack.length && j < needle.length) {
if (haystack[i] === needle[j]) {
i ++;
j ++;
} else if (j === 0) {
i ++;
} else {
j = patternTable[j - 1];
}
}
if (j === needle.length) {
return i - j;
}
return -1;
};
/**
* @param {string} word
*/
var buildPatternTable = function (word) {
let patternTable = [0];
let prefix = 0;
let suffix = 1;
while (suffix < word.length) {
if (word[prefix] === word[suffix]) {
patternTable[suffix] = prefix + 1;
suffix++;
prefix++;
} else if (prefix === 0) {
patternTable[suffix] = 0;
suffix++;
} else {
prefix = patternTable[prefix - 1];
}
}
return patternTable;
}
let a = 'abbababa';
console.log(strStr(a, 'bba') === a.indexOf('bba'));
console.log(strStr(a, 'aba') === a.indexOf('aba'));
console.log(strStr(a, 'absa') === a.indexOf('absa'));