close
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if len(needle) > len(haystack):
return -1
if len(needle) == 0:
return 0
for x in xrange(len(haystack) - len(needle) + 1):
if haystack[x] == needle[0]:
for y in xrange(1, len(needle) + 1):
if y == len(needle):
return x
if haystack[x+y] != needle[y]:
break
return -1
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if len(needle) > len(haystack):
return -1
if len(needle) == 0:
return 0
for x in xrange(len(haystack) - len(needle) + 1):
if haystack[x] == needle[0]:
for y in xrange(1, len(needle) + 1):
if y == len(needle):
return x
if haystack[x+y] != needle[y]:
break
return -1
PYTHONIC WAY:
return haystack.find(needle)
全站熱搜