使用双指针,比如:假设haystack长度为10,我就用一个长度为needle的尺子,从haystack的最开始的位置一步一步的往后移
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
res = []
n = len(haystack)
left = 0
right = len(needle)
while right > left and right <= n:
if haystack[left:right] == needle:
res.append(left)
break
else:
left += 1
right += 1
if len(res):
return res[0]
else:
return -1