|
| 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