Skip to content

Commit c3b815d

Browse files
committed
Add #0028 Find the Index of the First Occurrence in a String
1 parent 7e4cf29 commit c3b815d

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution:
2+
def strStr(self, haystack: str, needle: str) -> int:
3+
"""
4+
Implement strStr() function. Given two strings, return the index of the first occurrence
5+
of 'needle' in 'haystack', or -1 if 'needle' is not part of 'haystack'.
6+
7+
Parameters:
8+
haystack (str): The main string to search within.
9+
needle (str): The substring to search for.
10+
11+
Returns:
12+
int: The index of the first occurrence of 'needle' in 'haystack', or -1 if not found.
13+
"""
14+
15+
if len(haystack) < len(needle):
16+
return -1 # If haystack is shorter than needle, needle cannot be found
17+
18+
i = 0 # Pointer for haystack
19+
j = 0 # Pointer for needle
20+
needle_length = len(needle) # Length of the needle
21+
22+
while i < len(haystack):
23+
if haystack[i] == needle[j]:
24+
j += 1 # Move to the next character in needle
25+
if j == needle_length:
26+
return i - j + 1 # Found the needle, return the start index
27+
i += 1 # Move to the next character in haystack
28+
else:
29+
i = i - j + 1 # Reset haystack pointer to the next position after the last match
30+
j = 0 # Reset needle pointer
31+
32+
return -1 # Needle not found in haystack

0 commit comments

Comments
 (0)