题目:实现strStr()
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题意:
子字符串在字符串中第一次匹配的位置,如果不能匹配返回-1
方法一:性能65ms
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle and not haystack:
return 0
if not needle:
return 0
if not haystack and needle:
return -1
ans = -1
i, hay = 0, len(haystack)
k, nee = 0, len(needle)
for i in xrange(hay):
if haystack[i] == needle[k]:
ans = i
s = i+1
for k in xrange(1, nee):
if s >= hay:
return -1
if haystack[s] != needle[k]:
ans = -1
k = 0
break
s+=1
if ans != -1:
return ans
return ans
方法二:性能42ms
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)
使用haystack包的find()函数