-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplement strStr().py
55 lines (46 loc) · 1.07 KB
/
Implement strStr().py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def strStr(haystack: str, needle: str) -> int:
return haystack.find(needle)
'''def strStr( haystack: str, needle: str) -> int:
def LPS(needle):
j = 0
i = 1
m = len(needle)
lps = [0] * m
lps[0] = 0
while i < m:
if needle[i] != needle[j]:
if j == 0:
lps[i] = j
i += 1
else:
j = lps[j - 1]
else:
lps[i] = j + 1
i += 1
j += 1
return lps
if len(needle) == 0:
return 0
needle = list(needle)
lps = LPS(needle)
haystack = list(haystack)
n = len(haystack)
m = len(needle)
j = 0
i = 0
while (i < n):
if haystack[i] == needle[j]:
i += 1
j += 1
else:
if j != 0:
j = lps[j - 1]
else:
i += 1
if j == m:
return i - m
return -1'''
haystack = "hello"
needle = "bba"
ans = strStr(haystack, needle)
print(ans)