28实现strSTR()

class Solution:
def strStr(self, haystack: str, needle: str) -> int:
# 判断needle是否为NOne或者为空字符串
if not needle or len(needle) == 0:
return 0
# 定义两个变量,用来接收needle的长度
length,index = len(needle),0
# 进行循环,当index的值
while index <= len(haystack) - length:
# 判断是否可以匹配
if haystack[index : index + length] == needle:
return index
# 索引加一
else:
index += 1
# 代表匹配失败,返回-1
return -1

A = Solution()
print(A.strStr("hello","ll"))
print(A.strStr("helll","hahah"))
posted @ 2020-07-06 09:55  月为暮  阅读(211)  评论(0编辑  收藏  举报