当前位置:网站首页>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"))
边栏推荐
- 蓝桥历届真题-蛇形填数
- 行程和用户[阅读理解法]
- R language kaggle game data exploration and visualization
- 快来扔鸡蛋。
- Explanation of RTSP protocol
- GIN file upload and return
- Professor Chen Qiang's "Machine Learning and R Application" course Chapter 14 Assignment
- How to solve the 0x80070005 error when the computer is reinstalled and the system is restored
- RobotFramework 之 RF变量与标准库关键字使用
- 面试攻略系列(四)-- 你不知道的大厂面试
猜你喜欢
随机推荐
Q_06_05 文件结构
telnet+ftp to control and upgrade the device
pytest 之 重运行机制与测试报告
Professor Chen Qiang "application in machine learning and R" course chapter 17
FFmpeg相机花屏花图问题解决方法
19、学习MySQL 索引
JS轮播图实现
IDEA Gradle 常遇问题(一)
客户端连接rtsp的步骤
An Offer 21. Adjust the array in order to make odd in even the front (loop invariant)
GIN文件上传与返回
Process/Thread related in Sandbox - 1
Q_06_04 语句和其他构造
蓝桥杯线上模拟赛——Flex 经典骰子布局
Rmarkdown Tutorial
Oracle Recovery Tools修复空闲坏块
DCT变换与反变换
Q_04_05 使用Qubits
C#使用cersharp
RobotFramework 之 数据驱动
![行程和用户[阅读理解法]](/img/4b/77bba3c488b5410fdec5c3894c7421.png)








