Skip to content

Commit 0bb75bb

Browse files
authored
Create 28-Implement-strStr.py
1 parent 29f24ed commit 0bb75bb

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

28-Implement-strStr.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution:
2+
def strStr(self, haystack: str, needle: str) -> int:
3+
if needle == "": return 0
4+
lps = [0] * len(needle)
5+
6+
prevLPS, i = 0, 1
7+
while i < len(needle):
8+
if needle[i] == needle[prevLPS]:
9+
lps[i] = prevLPS + 1
10+
prevLPS += 1
11+
i += 1
12+
elif prevLPS == 0:
13+
lps[i] = 0
14+
i += 1
15+
else:
16+
prevLPS = lps[prevLPS - 1]
17+
18+
i = 0 # ptr for haystack
19+
j = 0 # ptr for needle
20+
while i < len(haystack):
21+
if haystack[i] == needle[j]:
22+
i, j = i + 1, j + 1
23+
else:
24+
if j == 0:
25+
i += 1
26+
else:
27+
j = lps[j - 1]
28+
if j == len(needle):
29+
return i - len(needle)
30+
return -1

0 commit comments

Comments
 (0)