题目描述
解题思路
解法一:双指针法
左指针的值从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