28. Implement strStr()
Leetcode link for this question
Discription:
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Analyze:
Code 1:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not haystack and needle or len(haystack)<len(needle):
return -1
if not haystack :
return 0
if haystack and not needle:
return 0
for i,v in enumerate(haystack):
if haystack[i:len(needle)+i]==needle:
return i
if i==len(haystack)-1:
return -1
Submission Result:
Status: Accepted
Runtime: 848 ms
Ranking: beats 0.30%
Code 2:
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
if not haystack:
return -1
if len(haystack)<len(needle):
return -1
i=0
while 1:
if i+len(needle)>len(haystack):
return -1
if haystack[i:i+len(needle)]==needle:
return i
i+=1
Submission Result:
Status: Accepted
Runtime: 64 ms
Ranking: beats 43.29%