We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent d6df4b0 commit 3d57742Copy full SHA for 3d57742
14. Questions/leetcode 28 - index of first occurrence.py
@@ -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