本文实例讲述了Python实现字符串的KMP算法。分享给大家供大家参考,具体如下:
KMP算法Python实现
今天研究KMP算法,看来很多版本,有不同的语言写的,但是感觉越看越乱,最后自己试着写一份进行总结
首先,KMP算法使字符串匹配中的优化算法,使原来的O(m*n)降到了O(m+n)
关于他的理解,我推荐先看视频,他讲的很清楚了。汪都能听懂的KMP字符串匹配算法
然后从可视化方面理解,推荐看看如何更好的理解和掌握 KMP 算法? - 佑子的回答 - 知乎容
最后从代码层理解Searching for Patterns | Set 2 (KMP Algorithm)
代码不要看太多别人的,我感觉好多人写的也有问题,我在自己运行处问题时,有看有些同学写的,被带到其他坑里了。。。
最后记录代码
'''
先求next数组
'''def next_list(pattern):
next=[]
pattern_list=list(pattern)
j=0
i=1
for s in range(len(pattern)): #第一位一直是0
if s==0:
next.append(0) #看第i个和第j个字母是否相同,如果相同,则累加
#同时i,j同时右移
elif(pattern_list[i]==pattern_list[j]):
next.append(j+1)
j+=1
i+=1
#如果不相同,则next为0,同时j也退回第一个位置,i继续前进一个位置
else:
next.append(0)
j=0
i=s+1
print(next) return next
next_list('ABABCABAB')
def kmp(text,pattern):
#text的位置
i=0
#pattern的位置
j=0
next=next_list(pattern) if(not(text and pattern)):
print('字符串为空,请输入字符串') elif(len(text)<len><p> </p>
<p><span style="font-size: 16px;">相关推荐:</span></p>
<p><a href="https://blog.csdn.net/starstar1992/article/details/54913261" target="_self" style="font-size: 16px; text-decoration: underline;"><span style="font-size: 16px;">KMP算法最浅显理解</span></a></p>
<p><a href="https://blog.csdn.net/liu940204/article/details/51318281" target="_self" style="font-size: 16px; text-decoration: underline;"><span style="font-size: 16px;">kmp算法详解</span></a></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill11111" title="python-flask-vue-creator"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e695c2374.jpg" alt="python-flask-vue-creator" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill11111" title="python-flask-vue-creator" class="overflowclass">python-flask-vue-creator</a>
<p class="overflowclass">创建 Flask + Vue.js 全栈项目,采用单端口架构、uv 依赖管理、结构化日志和生产级前端设计。当用户要求以下操作时触发:创建新的 Flask+Vue 项目、搭建 Web 应用、构建全栈 Python+Vue 应用、初始化 Flask Web 项目、设置单端口 Flask 前后端项目。触发词:新建项目、创建项目、搭建项目、Flask项目、Vue项目。</p>
</div>
<a rel="nofollow" href="/xiazai/skill11111" title="python-flask-vue-creator" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<p><a href="http://m.blog.csdn.net/newgreenfreshhand/article/details/5691318" target="_self" style="font-size: 16px; text-decoration: underline;"><span style="font-size: 16px;">KMP算法中最难理解的地方的理解</span></a></p>
<p><a href="https://blog.csdn.net/u012216287/article/details/48858433" target="_self" style="font-size: 16px; text-decoration: underline;"><span style="font-size: 16px;">kmp算法原理及实现</span></a></p>
<p><a href="https://blog.csdn.net/liu88010988/article/details/50789960" target="_self" style="font-size: 16px; text-decoration: underline;"><span style="font-size: 16px;">图解KMP算法</span></a></p>
<p><br></p></len>
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










