mycode 77.15%
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
len_1 , len_2 = len(haystack) , len(needle)
for i in range(len_1 - len_2 + 1):
if haystack[i:i+len_2] == needle:
return i
return -1
参考:
要习惯python的.find操作呀
Clarification:
What should we return when needle
is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle
is an empty string. This is consistent to C's strstr() and Java's indexOf().
class Solution(object):
def strStr(self, haystack, needle):
if not needle:
return 0
return haystack.find(needle)
手机扫一扫
移动阅读更方便
你可能感兴趣的文章