Title description:
Given a haystack string and a needle string, find the first position (starting from 0) where the needle string appears in the haystack string. If it does not exist, it returns -1.
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Problem-solving ideas:
Method 1: Match the substrings one by one
The sliding window of length L is gradually moved along the haystack string, and the substring in the window is compared with the needle string. The time complexity is O((N−L)L)
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
L, n = len(needle), len(haystack)
for start in range(n - L + 1):
if haystack[start: start + L] == needle:
return start
return -1
Method 2: Double pointer search
Only when the first character of the substring is the same as the first character of the needle string does it need to be compared. It is compared character by character, and it terminates immediately if it does not match. Note that the pointer needs to be traced when it does not match.
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
l1,l2=len(haystack),len(needle)
if l2==0:
return 0
i=0
while i<l1-l2+1:
p=i
j,cur_len=0,0
while i<l1-l2+1 and haystack[i]!=needle[0]:
i+=1
while i<l1 and j<l2 and haystack[i]==needle[j]:
i+=1
j+=1
cur_len+=1
#print(i,j,cur_len)
if cur_len==l2:
return i-l2
#i=i-j+1 #回溯到初始位置的下一个
i=p+1
return -1