class Solution:
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if needle == "" or needle == haystack:
return 0
elif len(needle)> len(haystack):
return -1
else:
for i in range(len(haystack)-1):
if haystack[i] == needle[0]:
n = len(needle)
#print(haystack[i:i+n])
if haystack[i:i+n] == needle:
return i
else:
pass
return -1
思路:遇到与needle首字符相同,则比较是否有包含。
注意:空字符串,needle更长,单字符的特殊情况,注意字符串切片用法
拓展:KMP算法