KMP算法
KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R.Pratt提出的,因此人们称它为克努特—莫里斯—普拉特操作(简称KMP算法)。KMP算法的核心是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。具体实现就是通过一个next数组来实现,函数本身包含了模式串的局部匹配信息。KMP算法的时间复杂度O(m+n)。
python代码实现
# str1 和 str2
def KMP_index(str1, str2):
i1, i2 = 0, 0
next_list = GetNextArray(str2)
while i1 < len(str1) and i2 < len(str2):
if str1[i1] == str2[i2]:
i1 += 1
i2 += 1
elif next_list[i2] == -1:
i1 += 1
else:
i2 = next_list[i2]
return i1 - i2 if i2 == len(str2) else -1
def GetNextArray(str2):
"""
构建netx_list数组
:param str2:
:return:
"""
if len(str2) == 1:
return -1
next_list = [-1] * len(str2)
next_list[0], next_list[1] = -1, 0
i, cn = 2, 0
while i < len(str2):
if str2[i - 1] == str2[cn]:
cn += 1
next_list[i] = cn
i += 1
elif cn > 0:
cn = next_list[cn]
else:
next_list[i] = 0
i += 1
return next_list
if __name__ == '__main__':
string1 = "adsfdasfsdf"
string2 = "asf"
a = KMP_index(string1,string2)
print(a)