Problem:
Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Idea: Use two points to go through these two string individually.
Solution:
class Solution(object):
def strStr(self, haystack, needle):
i=j=
0
lenhaystack = len(haystack)
lenneedle = len(needle)
if lenneedle ==
0:
return 0
while j!= lenhaystack:
if haystack[j] == needle[i]:
if i+
1 == lenneedle:
return j-i
else:
i +=
1
j +=
1
elif i !=
0:
j = j-i+
1
i =
0
else:
j +=
1
return -
1
转载请注明原文地址: https://ju.6miu.com/read-6279.html