实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll" 输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba" 输出: -1
方法一:直接str.find()函数
执行用时 : 52 ms, 在Implement strStr()的Python3提交中击败了88.64% 的用户
内存消耗 : 13.4 MB, 在Implement strStr()的Python3提交中击败了34.03% 的用户
class Solution(object):
def strStr(self,haystack,needle):
res = haystack.find(needle)
return res
方法二:
class Solution(object):
def strStr(self,haystack,needle):
if not needle:
return 0
lenh = len(haystack)
lenn = len(needle)
if needle not in haystack:
return -1
if lenh<lenn:
return -1
if lenh == lenn:
return 0 if haystack==needle else -1
for i,d in enumerate(haystack):
if lenh-i < lenn:
return -1
if d == needle[0]:
if haystack[i:i+lenn] == needle:
return i
s = Solution()
res = s.strStr("mississippi","a")
print(res)
本文详细解析了如何实现strStr()函数,该函数用于在haystack字符串中查找needle字符串首次出现的位置。通过两个示例展示了函数的使用,同时提供了两种实现方法:使用内置find()函数和自定义遍历比较。第一种方法简洁高效,第二种方法则更深入地理解字符串匹配过程。
254

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



