-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindIndexString.js
More file actions
37 lines (32 loc) · 932 Bytes
/
FindIndexString.js
File metadata and controls
37 lines (32 loc) · 932 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
37
// Given two strings needle and haystack, return the index of the first occurrence of needle in haystack,
// or -1 if needle is not part of haystack.
/**
* @param {string} haystack
* @param {string} needle
* @return {number}
*/
// Im going with two pointer
var strStr = function(haystack, needle) {
let p = 0;
let startingIndex = 0;
for (let i = 0; i < haystack.length; i++) {
if (haystack[i] === needle[p]) {
if (p === 0) {
startingIndex = i;
}
p++;
if (p === needle.length) {
return startingIndex;
}
} else {
if (p > 0) {
i = startingIndex;
}
p = 0;
startingIndex = -1;
}
}
return -1;
};
console.log(strStr("leetcode", "code"))
// Couldve used the javascript built in method .substring but i decided to do it manually lol