【Leetcode 28】实现strStr()

题目描述

在这里插入图片描述
在这里插入图片描述

解题思路

解法一:双指针法

在这里插入图片描述
左指针的值从haystack的0位置开始,右指针的初始值为needle的长度,根据需要匹配(ll)的长度来确定滑动的长度。

  • 匹配needle是否与haystack相等,如果相等就返回L的值,即为出现的第一个位置
  • 如果不相等,左指针L和右指针R右移,直至遍历完整个字符串

python代码

class Solution():
	def strStr(self, haystack: str, needle: str) -> int:
        if not needle:
            return 0
        L = 0
        R = len(needle)
        while R <= len(haystack):
            if haystack[L:R] == needle:
                return L
            else:
                L += 1
                R += 1
        return -1
发布了56 篇原创文章 · 获赞 1 · 访问量 1661

猜你喜欢

转载自blog.csdn.net/weixin_44549556/article/details/105489687