題目描述
解題思路
解法一:雙指針法
左指針的值從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