- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathimplement_strStr.py
26 lines (23 loc) · 991 Bytes
/
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
classSolution:
defstrStr(self, haystack: str, needle: str) ->int:
# be careful: the edge cases
# what if haystack is empty? and what if needle is empty?
iflen(needle) ==0:
return0
iflen(haystack) ==0andlen(needle) !=0:
return-1
# O(mn), Brute Force
# it is sufficient to solve it using the most direct method
# be careful: need to 'plus one for the 1st loop'!!
# for index in range( len(haystack) - len(needle)):
forindexinrange( len(haystack) -len(needle) +1):
forjinrange( len(needle) ):
ifhaystack[index+j] ==needle[j]:
pass
else:
break
# the occurence of needle!!! (without a break)
ifj== (len(needle) -1):
returnindex
# no occurence of needle, return -1
return-1