-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path28. Implement strStr().js
50 lines (40 loc) · 1.14 KB
/
28. 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
/*
28. Implement strStr()
https://leetcode.com/problems/implement-strstr/
https://leetcode.com/problems/implement-strstr/discuss/2400787/java-script-fastest-and-easiest-way-to-solve-this-problem-with-on
*/
/* TIME COMPLEXITY O(logn) */
/*
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
*/
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
var strStr = function (haystack, needle) {
for (let i = 0; i < (haystack.length - needle.length) + 1; i++) {
//Here we use for loop start with 0 to ith window
if (haystack.slice(i, needle.length + i) === needle) {
// Return ith window array
/*
missi
issis
ssiss
sissi
issip
ssipp
sippi
*/
/* return one of them ith window array if it's satisfy the condition */
return i;
}
}
return -1; // Return -1 if non of them satisfy the condition
};
console.log(strStr("mississippi", "issip"));