这个题解使用了 KMP 算法来解决字符串匹配问题。首先通过 gen_nxt() 函数生成 needle 字符串的 next 数组,next[i] 表示 needle[0:i] 这个子串的最长相等前后缀的长度。然后在 search() 函数中,使用 next 数组来优化匹配过程,当出现字符不匹配时,通过 next 数组将 needle 向右移动尽可能远的距离,避免了暴力解法中的重复匹配,从而提高了匹配效率。
时间复杂度: O(m+n)
空间复杂度: O(m)
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
nxt = []
def search():
tar = 0
pos = 0
while tar < len(haystack):
if haystack[tar] == needle[pos]:
tar += 1
pos += 1
elif pos != 0:
pos = nxt[pos-1] # 如果不匹配,则通过 next 数组将 needle 向右移动
else:
tar += 1
if pos == len(needle): # 匹配成功
return tar - pos
return -1
def gen_nxt():
nxt.append(0)
x = 1
now = 0 # next[x-1]
while x < len(needle):
if needle[x] == needle[now]: # 如果相等,则 next[x] = now + 1
x += 1
now += 1
nxt.append(now)
elif now != 0: # 如果不相等,则通过 next 数组移动 now 指针
now = nxt[now-1]
else: # 如果 now 已经为 0,则 next[x] = 0
x += 1
nxt.append(0)
gen_nxt() # 生成 next 数组
return search() # 进行匹配