-
Notifications
You must be signed in to change notification settings - Fork 20
/
ImplementStrStr.js
54 lines (45 loc) · 1.02 KB
/
ImplementStrStr.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
/**
* Implement strStr().
* Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
*
* Accepted.
*/
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
let strStr = function (haystack, needle) {
if (haystack == null || needle == null || needle.length > haystack.length) {
return -1;
}
if (haystack.length === 0 || needle.length === 0) {
return 0;
}
for (let i = 0; i <= haystack.length - needle.length; i++) {
if (haystack.substring(i, i + needle.length) === needle) {
return i;
}
}
return -1;
};
if (strStr("aaab", "b") === 3) {
console.log("pass")
} else {
console.error("failed")
}
if (strStr("", "") === 0) {
console.log("pass")
} else {
console.error("failed")
}
if (strStr("", "a") === -1) {
console.log("pass")
} else {
console.error("failed")
}
if (strStr("whats up", "s ") === 4) {
console.log("pass")
} else {
console.error("failed")
}