Skip to content

Commit 3d57742

Browse files
committedMar 3, 2023
added: index of first occurrence
1 parent d6df4b0 commit 3d57742

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# find the index of the first occurrence of a string | leetcode 28 | https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/
2+
# sliding window to match each character of the haystack with the needle; no slices.
3+
4+
class Solution:
5+
def strStr(self, haystack: str, needle: str) -> int:
6+
# ----- using regex -----
7+
# if needle == '':
8+
# return 0
9+
10+
# import re
11+
# match = re.search(needle, haystack)
12+
# return match.start() if match else -1
13+
14+
# ----- using sliding windows -----
15+
ptrL, ptrR = 0, 0
16+
N_needle, N_haystack = len(needle), len(haystack)
17+
while ptrR < N_haystack:
18+
if haystack[ptrR] == needle[ptrR - ptrL]:
19+
ptrR += 1
20+
if ptrR - ptrL > N_needle - 1:
21+
return ptrL
22+
else:
23+
ptrR = ptrL + 1
24+
ptrL += 1
25+
26+
return -1

0 commit comments

Comments
 (0)
Failed to load comments.