当前位置:网站首页>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"))
边栏推荐
- 缓存和数据库一致性问题
- Sandbox中的进程/线程相关-1
- The sword refers to Offer 56 - II. Number of occurrences of a number in an array II (bit operation)
- Professor Chen Qiang the machine learning and R application course chapter 18 assignments
- gin's middleware and routing grouping
- Come and throw eggs.
- kustomize entry example and basic syntax instructions
- 自己做了个nodejs+epxress+mysql的小项目,怎么才能让别人通过互联网访问呢?
- FFmpeg多媒体文件处理(ffmpeg操作目录及list的实现)
- 利用信号灯和共享内存实现进程间同步通信
猜你喜欢
FFmpeg multimedia file processing (implementation of ffmpeg operation directory and list)
Unicom network management protocol block diagram
FFmpeg multimedia file processing (the basic concept of ffmpeg processing stream data)
Final assignment of R language data analysis in a university
蓝桥历届真题-跑步锻炼
蓝桥历届真题-蛇形填数
易语言获取cookie
error Trailing spaces not allowed no-trailing-spaces 9:14 error Unexpected trailing comma
GET POST PUT DELETE request in GIN
【瑞吉外卖】day05:增、删、改、查分类以及公共字段自动填充
随机推荐
Q_06_02 类型模型
ArcEngine(十)创建矢量图层
IDEA Gradle 常遇问题(一)
Clock frequency and baud rate count for serial communication in FPGA
CPU-MIPS32 instruction architecture (unlocked pipeline microprocessor)
剑指 Offer 43. 1~n 整数中 1 出现的次数(递归、数学)
NFS pays special attention to the problem of permissions
GIN file upload and return
pytest 筛选用例
WPF 系统托盘 图标闪烁
Ledong Fire Rescue Brigade was invited to carry out fire safety training for cadres
Unity3d_API_Gyroscope 陀螺仪的接口
蓝桥历届真题-蛇形填数
Oracle Recovery Tools修复空闲坏块
Professor Chen Qiang's "Machine Learning and R Application" course Chapter 16 Assignment
IDEA Gradle 常遇问题(二)(持续更新)
企业公众号开通微信支付
pytest 基础认知
ArcEngine(八) 选择要素并高亮显示
R language kaggle game data exploration and visualization