Skip to content

Commit e7607e1

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.9 MB (27.12%)
1 parent dca47fc commit e7607e1

File tree

1 file changed

+13
-12
lines changed
  • 0028-find-the-index-of-the-first-occurrence-in-a-string

1 file changed

+13
-12
lines changed
Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,19 @@
1-
# Approach - Sliding Window
1+
# Approach 1: Sliding Window
2+
3+
# Time: O(mn)
4+
# Space: O(1)
25

36
class Solution:
47
def strStr(self, haystack: str, needle: str) -> int:
5-
if not needle:
6-
return 0
7-
8-
n, k = len(haystack), len(needle)
9-
10-
if haystack[0 : k] == needle:
11-
return 0
12-
13-
for i in range(k, n):
14-
if haystack[i - k + 1 : i + 1] == needle:
15-
return i - k + 1
8+
m = len(needle)
9+
n = len(haystack)
10+
11+
for window_start in range(n - m + 1):
12+
for i in range(m):
13+
if needle[i] != haystack[window_start + i]:
14+
break
15+
if i == m - 1:
16+
return window_start
1617

1718
return -1
1819

0 commit comments

Comments
 (0)