核心原理可以查看下面的博文
字符串匹配——一文吃透KMP算法
下面是本人用python实现的代码
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 10 20:01:49 2018
@author: liweishen
"""
def kmp(t,p):
n,m=len(t),len(p)
next_list=gen_next(p)
i=0
while i<n:
q=0
#寻找从第i各字符开始,互相匹配的字符串有多长
while t[i+q]==p[q]:
q=q+1
if q==m:
break
#当找到匹配的子串
if q==m:
print("pattern occurs with shift: ",i)
break
else:
i=i+q-next_list[q]+1
#用来生成next数组,判别最长相同前后缀
def gen_next(p):
k=0
m=len(p)
next_list=[-1]*m #初始化一个next数组
next_list[0]=0 #然后第一位是0,表示只有第一个元素时,最长相同为0
for q in range(1,m):
while k>0 and p[q]!=p[k]:
k=next_list[k-1]
if p[q]==p[k]:
k=k+1
next_list[q]=k
return next_list
kmp("sdfabcesfdsfabcvabcsdfabcesfdsfabcewrtabdjkldfgyhuisdfhsaf","abcesfdsfabcewrt")