-
Notifications
You must be signed in to change notification settings - Fork 0
/
28.ts
33 lines (32 loc) · 906 Bytes
/
28.ts
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
// 28. Find the Index of the First Occurrence in a String
// 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.
function strStr(haystack: string, needle: string): number {
let j = 0;
let index = 0;
let next = 0;
let foundNext = false;
for (let i = 0; i < haystack.length; i++) {
if (haystack.charAt(i) === needle.charAt(j)) {
if(j === 0) {
index = i;
}
if(haystack.charAt(i) === haystack.charAt(index) && !foundNext) {
foundNext = true;
next = i;
}
j++;
if (j === needle.length) {
return index;
}
}
else {
j = 0;
if(foundNext) {
i = next;
foundNext = false;
}
}
}
return -1;
};