-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path28.js
47 lines (42 loc) · 761 Bytes
/
28.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
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
const strStr = (haystack, needle) => {
if (needle.length > haystack.length) {
console.log('-1');
return -1;
}
let i = 0;
let j = 0;
let curLen = 0;
let maxLen = needle.length;
let index = -1;
while (i < haystack.length) {
if (haystack[i] === needle[j]) {
if (index === -1) {
index = i;
}
curLen += 1;
if (curLen === maxLen) {
return index;
}
j += 1;
i += 1;
} else {
if (curLen > 0) {
curLen = 0;
j = 0;
i = index + 1;
index = -1;
} else {
i += 1;
}
}
}
if (curLen !== maxLen) {
index = -1;
}
return index;
};