We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent dca47fc commit e7607e1Copy full SHA for e7607e1
0028-find-the-index-of-the-first-occurrence-in-a-string/solution.py
@@ -1,18 +1,19 @@
1
-# Approach - Sliding Window
+# Approach 1: Sliding Window
2
+
3
+# Time: O(mn)
4
+# Space: O(1)
5
6
class Solution:
7
def strStr(self, haystack: str, needle: str) -> int:
- if not needle:
- return 0
-
8
- n, k = len(haystack), len(needle)
9
10
- if haystack[0 : k] == needle:
11
12
13
- for i in range(k, n):
14
- if haystack[i - k + 1 : i + 1] == needle:
15
- 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:
16
+ return window_start
17
18
return -1
19
0 commit comments