28. Implement strStr()
# Easy
In order to be more efficiency, only compare elements of strStr()
in [0: len(strStr)-len(needle)+1]
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
# edge case
if len(needle) == 0:
return 0
# regular case
i = 0
j = 0
flag = -1 # the elements are not same
while i < len(haystack)-len(needle)+1:
if haystack[i] == needle[0]:
x = i+1
y = 1
while x < len(haystack) and y < len(needle):
if haystack[x] == needle[y]:
x += 1
y += 1
else:
break
if y == len(needle):
return i
i += 1
return -1
Last updated
Was this helpful?