当前位置:网站首页>KMP方法
KMP方法
2022-08-09 13:08:00 【风华明远】
KMP是一种字符串搜索算法。网络上查到的2种算法都存在bug,对于“aaa"这种特殊情况会出现错误或者死循环。
下面是改进的方法:
def build_patter(s):
n = len(s)
next = [0]*n
i = 1
j = 0
while i < n:
if j == 0 and s[i] != s[j]:
next[i]=0
i += 1
elif j !=0 and s[i] !=s[j]:
j = next[j-1]
elif s[j] == s[i]:
j+=1
next[i]=j
i+=1
return next
def kmp(p,s):
if s == "":
return -1
next = build_patter(s)
p_len = len(p)
s_len = len(s)
i = j = 0
while i < p_len:
if p[i] == s[j]:
i +=1
j +=1
if j >=s_len:
return i - s_len
elif next[j] == 0:
i+=1
j = 0
else:
j = next[j-1]
return -1
print(kmp("asdassaaababababcabcfffj","abab"))
边栏推荐
猜你喜欢

RobotFramework简介

群组行动控制--自动队列化实现策略

现在40系显卡都快出来了,为何1060型号的显卡还有这么多人用?

How to solve the 0x80070005 error when the computer is reinstalled and the system is restored

kustomize entry example and basic syntax instructions

Oracle Recovery Tools修复空闲坏块

FFmpeg多媒体文件处理(ffmpeg操作目录及list的实现)

19、学习MySQL 索引

Final assignment of R language data analysis in a university

pytest 之 fixture参数化
随机推荐
pytest 之 fixture的调用
Q_06_03 表达式
ArcEngine(八) 选择要素并高亮显示
技嘉显卡 RGBFusion 不能调光解决方法
19、学习MySQL 索引
Microsoft 10/11 命令行打开系统设置页(WUAP,!WIN32)
NC7 买卖股票的最好时机(一)
Q_08 更多信息
NC15 求二叉树的层序遍历
Explanation of RTSP protocol
NC40 链表相加(二)
Professor Chen Qiang's "Machine Learning and R Application" course Chapter 15 Homework
Final assignment of R language data analysis in a university
RTP打包发送H.264
Process/Thread Related in Sandbox - 2
glibc memory management model freeing C library memory cache
昇腾AI开发者创享日南京站!一起CANN机器狗+AI机械臂实现硬核智慧救援!燃爆现场~
微服务+微信小程序实现社区服务
pytest 之 allure报告
LeetCode 37.解数独