在字符串s中,查找字符串a的索引,返回为索引数组
def compute_lps_array(a):
lps = [0] * len(a)
length = 0
i = 1
while i < len(a):
if a[i] == a[length]:
length += 1
lps[i] = length
i += 1
else:
if length != 0:
length = lps[length - 1]
else:
lps[i] = 0
i += 1
return lps
def KMP_search(s, a):
len_s = len(s)
len_a = len(a)
lps = compute_lps_array(a)
indices = []
i = j = 0
while i < len_s:
if a[j] == s[i]:
i += 1
j += 1
if j == len_a:
indices.append(i - j)
j = lps[j - 1]
elif i < len_s and a[j] != s[i]:
if j != 0:
j = lps[j - 1]
else:
i += 1
return indices