Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example
Input: haystack = “hello”, needle = “ll”
Output: 2
Solution
@直接遍历主干
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle=='':
return 0
if len(haystack)<len(needle):
return -1
flag = 0
for i in range(len(haystack)):
if haystack[i]==needle[0] and len(haystack)-i>=len(needle):
flag = 0
for j in range(len(needle)):
if i+j+1>len(haystack) or haystack[i+j]!=needle[j]:
flag = 1
break
if flag==0:
return i
##很重要的边界条件,可显著降低运行时间
elif len(haystack)-i<len(needle):
return -1
return -1
#切片很简便
class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if len(haystack)<len(needle):
return -1
for i in range(len(haystack)-len(needle)+1):
if haystack[i:i+len(needle)]==needle:
return i
return -1