-
Notifications
You must be signed in to change notification settings - Fork 154
/
implement-strstr.js
115 lines (103 loc) · 2.13 KB
/
implement-strstr.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/**
* Implement strStr()
*
* Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
*
* Example 1:
*
* Input: haystack = "hello", needle = "ll"
* Output: 2
*
* Example 2:
*
* Input: haystack = "aaaaa", needle = "bba"
* Output: -1
* Clarification:
*
* What should we return when needle is an empty string? This is a great question to ask during an interview.
*
* For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr()
* and Java's indexOf().
*/
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
const strStr = (haystack, needle) => {
for (let i = 0; ; i++) {
for (let j = 0; ; j++) {
if (j === needle.length) return i;
if (i + j === haystack.length) return -1;
if (needle[j] !== haystack[i + j]) break;
}
}
};
/**
* KMP Algorithm
*
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
const strStrKMP = (haystack, needle) => {
const m = haystack.length;
const n = needle.length;
if (n === 0) {
return 0;
}
const lps = getLPS(needle);
let i = 0;
let j = 0;
while (i < m) {
if (haystack[i] === needle[j]) {
i++;
j++;
// found the needle in haystack!
if (j === n) {
return i - n;
}
} else if (j > 0) {
j = lps[j - 1];
} else {
i++;
}
}
return -1;
};
/**
* KMP algorithm to get the longest prefix and suffix count
*
* len = lps[len - 1];
*
* From:
* len-1
* |
* lps: ++++++++x________++++++++y
* | |
* len i
* To:
*
* lps: ****y________________****y
* | |
* len i
*
* @param {string} s
* @return {number[]}
*/
const getLPS = s => {
const lps = Array(s.length).fill(0);
let i = 1;
let len = 0;
while (i < s.length) {
if (s[i] === s[len]) {
lps[i++] = ++len;
} else if (len > 0) {
len = lps[len - 1];
} else {
i++;
}
}
return lps;
};
export { strStr, strStrKMP };