Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Subscribe to see which companies asked this question
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
l_h = len(haystack)
l_n = len(needle)
if l_h == 0:
if l_n == 0:
return 0
return -1
if l_n == 0:
return 0
for i in range(l_h):
if needle[0] == haystack[i]:
flag = True
if i + l_n > l_h:
break
for j in range(l_n):
if needle[j] != haystack[i+j]:
flag = False
break
if flag:
return i
return -1
本来想偷个懒,用try语句处理数组越界问题,但是超时了,还是老老实实判断边界条件吧。