实现 strStr() 函数
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。

解决这个问题的主要思路是:把needle作为一个整体,从haystack索引0开始,切出和needle一样长度的字符串,比较两者是否一致,否则将索引移到下一位
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
m = 0
x = len(haystack) # haystack长度
y = len(needle) # needle长度
if x == 0 and y != 0:
return -1
elif y > x :
return -1
elif x != 0 and y == 0:
return 0
elif x == 0 and y == 0:
return 0
while True :
if y > x - m :# 如果 needle 长度比 haystack 剩下的要长
return -1 # 直接返回-1
maybe = haystack[m : m + y] # 切片
if maybe == needle :
return m
else :
m += 1
题库来源:https://leetcode-cn.com
本文详细解析了如何实现strStr()函数,该函数用于在haystack字符串中查找needle字符串首次出现的位置。通过对比子串,文章提供了一种有效的解决方案,并讨论了边界情况。
24

被折叠的 条评论
为什么被折叠?



