当前位置:网站首页>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"))
边栏推荐
- Ledong Fire Rescue Brigade was invited to carry out fire safety training for cadres
- NC193 二叉树的前序遍历
- Professor Chen Qiang "application in machine learning and R" course chapter 17
- LeetCode 37. Solve Sudoku
- RobotFramework 之 资源文件
- 蓝桥历届真题-门牌制作
- GIN初探,环境安装
- NC84 完全二叉树结点数
- Professor Chen Qiang the machine learning and R application course chapter 18 assignments
- glibc memory management model freeing C library memory cache
猜你喜欢
随机推荐
RobotFramework 之 库与关键字
Q_06_05 文件结构
NC7 买卖股票的最好时机(一)
pytest 基础认知
GIN file upload and return
FFmpeg多媒体文件处理(ffmpeg操作目录及list的实现)
Unity3d_API_Gyroscope 陀螺仪的接口
RTSP协议的实现
对百度的内容进行修改
Come and throw eggs.
群组行动控制--自动队列化实现策略
DCT变换与反变换
GET POST PUT DELETE request in GIN
RTP打包发送H.264
pytest 之 fixture的定义及作用域
FFmpeg多媒体文件处理(ffmpeg处理流数据的基本概念)
音视频录入的pts和dts问题
pytest 与 unittest 的区别
Realization of RTSP Protocol
Professor Chen Qiang the machine learning and R application course chapter 18 assignments