-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathimplement-strstr.js
52 lines (46 loc) · 1.1 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
// Solution 1
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
return haystack.indexOf(needle);
};
// Solution 2
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
if (haystack === "") {
return needle === "" ? 0 : -1;
}
if (needle === "") {
return 0;
}
//Guarantee haystack non-empty
var len1 = haystack.length;
var len2 = needle.length;
if (len1 < len2) {
return -1;
} else if (len1 === len2) {
return haystack === needle ? 0 : -1;
} else {
//guarantee haystack is longer than needle
var startpoint = 0;
while (startpoint <= len1 - len2) {
var parent = startpoint, child = 0;
while (haystack[parent] === needle[child]) {
parent++;
child++;
if (child === len2) {
return startpoint;
}
}
startpoint++;
}
return -1;
}
};