KMP算法
来源:互联网 发布:青山水利造价软件 编辑:程序博客网 时间:2024/06/09 18:58
KMP算法是一种改进的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R.Pratt同时发现,因此人们称它为克努特——莫里斯——普拉特操作(简称KMP算法)。KMP算法的关键是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。具体实现就是实现一个next()函数,函数本身包含了模式串的局部匹配信息。时间复杂度O(m+n)。
一个解释很详细的博客:
KMP算法详解
代码实现:
package KMP;public class KMP { public static void main(String[] args) { } public static int KMP(String ts , String ps){ char[] t = ts.toCharArray(); char[] p = ps.toCharArray(); int[] next = new int[p.length]; int i=0 ; //主串的位置 int j=0; //模式串的位置 next = getNext(p); //获取next数组 while(i<t.length&&j<p.length){ if(j==-1||t[i]==p[j]){ //当j=-1时,代表第一位就不匹配,所有要移动的 // 是i,j也要归0 i++; j++; }else{ j = next[j]; //不匹配了,j移到k的位置 } } if(j == p.length){ return i-j; }else { return -1; } } private static int[] getNext(char[] p){ int[] next = new int[p.length]; next[0]=-1; int j =0; int k=-1; while(j<p.length-1){ if(k==-1||p[j]==p[k]){ if(p[++j]==p[++k]){ next[j]=next[k]; }else{ next[j]=k; } }else{ k = next[k]; } } return next; }}
0 0
- KMP算法详解 【KMP】
- 【KMP】KMP算法模板
- KMP hihoCoder1015 KMP算法
- kmp算法
- KMP算法
- KMP算法
- KMP算法
- KMP算法
- KMP 算法
- kmp算法
- KMP算法
- kmp算法
- KMP算法
- KMP算法
- kmp算法
- kmp算法
- KMP算法
- KMP算法
- 学习Weblogic的学习之一
- python——高阶函数——闭包 装饰
- intellij idea maven 使用
- Search Insert Position
- java将16进制与10进制互相转换
- KMP算法
- mysql:command not found问题解决
- Python 将json格式文件转存为RDF格式文件
- POJ 3468 A Simple Problem with Integers(线段树)
- maven错误处理
- springboot-mybatis—多数据源
- google浏览器提示https不是安全链接
- C# 验证码生成类
- linux下tar.gz、tar、bz2、zip等解压缩、压缩命令小结