diff --git a/0028-find-the-index-of-the-first-occurrence-in-a-string/solution.py b/0028-find-the-index-of-the-first-occurrence-in-a-string/solution.py index 22fb048..03201a1 100644 --- a/0028-find-the-index-of-the-first-occurrence-in-a-string/solution.py +++ b/0028-find-the-index-of-the-first-occurrence-in-a-string/solution.py @@ -1,18 +1,19 @@ -# Approach - Sliding Window +# Approach 1: Sliding Window + +# Time: O(mn) +# Space: O(1) class Solution: def strStr(self, haystack: str, needle: str) -> int: - if not needle: - return 0 - - n, k = len(haystack), len(needle) - - if haystack[0 : k] == needle: - return 0 - - for i in range(k, n): - if haystack[i - k + 1 : i + 1] == needle: - return i - k + 1 + m = len(needle) + n = len(haystack) + + for window_start in range(n - m + 1): + for i in range(m): + if needle[i] != haystack[window_start + i]: + break + if i == m - 1: + return window_start return -1