leetcode:实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr
移动 p1指针,直到 pn 所指向位置的字符与 needle 字符串第一个字符相等。
通过 p1,p2,curr_len 计算匹配长度。
如果完全匹配(即 curr_len == L),返回匹配子串的起始坐标(即 p1 - L)。
如果不完全匹配,回溯。使 p1 = p1 - curr_len + 1, p2 = 0, curr_len = 0。
class Solution: def strStr(self, haystack: str, needle: str) -> int: l1,l2=len(haystack),len(needle) if l2==0: return 0 p1=0 while p1<l1-l2+1: p2,length=0,0 while p1<l1-l2+1 and haystack[p1]!=needle[0]: #这里p1小于两个字符串长度差值即可 p1+=1 while p1<l1 and p2<l2 and haystack[p1]==needle[p2]: #这里p1<l1因为需要比较完l1字符串 p1+=1 p2+=1 length+=1 if length==l2: return p1-l2 p1=p1-p2+1 #回溯 return -1

浙公网安备 33010602011771号