forked from realpacific/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathneedle.py
41 lines (36 loc) · 1.12 KB
/
needle.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
# def strStr(haystack: str, needle: str) -> int:
# ned_len = len(needle)
# if ned_len == 0 or needle == haystack:
# return 0
# if ned_len > len(haystack):
# return -1
# for i in range(0, len(haystack)):
# if haystack[i: i + ned_len] == needle:
# return i
# return -1
def strStr(haystack: str, needle: str) -> int:
ned_len = len(needle)
if ned_len == 0 or needle == haystack:
return 0
if ned_len > len(haystack):
return -1
i = 0
while i < len(haystack):
window = haystack[i: i + ned_len]
if window == needle:
return i
elif window.find(needle[0]) > 0:
i = i + window.find(needle[0])
else:
i += 1
# for i in range(0, len(haystack)):
# if haystack[i: i + ned_len] == needle:
# return i
return -1
if __name__ == "__main__":
print(strStr("hellove", 'lov'))
print(strStr("hellove", 'e'))
print(strStr("hellove", 'ov'))
print(strStr("hello", 'zzzzzzzll'))
print(strStr("hello", 'hello'))
print(strStr(haystack="aaaaa", needle="bba"))