-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathimplement_strstr.js
More file actions
36 lines (32 loc) · 971 Bytes
/
implement_strstr.js
File metadata and controls
36 lines (32 loc) · 971 Bytes
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
var strStr = function (haystack, needle) {
// Base condition
if (haystack == null || needle == null) {
return -1;
}
// Special case
if (haystack === needle) {
return 0;
}
// length of the needle
const needleLength = needle.length;
// Loop through the haystack and slide the window
for (let i = 0; i < haystack.length - needleLength + 1; i++) {
// Check if the substring equals to the needle
if (haystack.substring(i, i + needleLength) === needle) {
return i;
}
}
return -1;
};
let haystackString = "hello";
let needleString = "ll";
console.log(strStr(haystackString, needleString));
haystackString = "aaaaa";
needleString = "bba";
console.log(strStr(haystackString, needleString));
haystackString = "";
needleString = "";
console.log(strStr(haystackString, needleString));
haystackString = "abc";
needleString = "c";
console.log(strStr(haystackString, needleString));