KMP算法实现
来源:互联网 发布:建筑设计模型制作软件 编辑:程序博客网 时间:2024/06/03 18:33
关于KMP算法网上已经有了很详细的解释,这里我不在解释,直接用Java写出KMP算法的实现代码供读者参考;
import java.util.*;public class KMP { public static int kmp(String str,String match){ if(str==null || match==null || match.length()<1 || str.length()<match.length())return -1; int next[]=getNextArray(match); int sp=0,mp=0; while(sp<str.length() && mp<match.length()){ if(str.charAt(sp)==match.charAt(mp)){ sp++; mp++; } else if(next[mp]==-1){ sp++; }else { mp=next[mp]; } } return mp==match.length()?sp-mp:-1; } public static int[] getNextArray(String match){ int next[]=new int[match.length()]; next[0]=-1; if(match.length()==1)return next; next[1]=0; int pos=2; int cn=0; while(pos<next.length){ if(match.charAt(cn)==match.charAt(pos-1)) next[pos++]=++cn; else if(cn>0) cn=next[cn]; else next[pos++]=0; } return next; }public static void main(String[] args) {// TODO 自动生成的方法存根 Scanner scan=new Scanner(System.in); String str=scan.nextLine(); String match=scan.nextLine(); System.out.println(kmp(str,match));}}
测试样例:
abcdefg
bc
1
0 0
- KMP算法及改进KMP算法实现
- [数据结构]KMP算法实现
- KMP算法的实现
- KMP算法实现
- KMP算法实现
- KMP 算法实现
- kmp算法实现
- KMP算法实现
- KMP算法和实现
- KMP算法实现
- KMP算法及实现
- KMP算法的实现
- KMP算法实现
- java实现kmp算法
- KMP算法C++实现
- KMP算法c++实现
- KMP算法java实现
- kmp算法实现
- 为什么构造函数不能是虚函数
- C++语法入门 - 持续更新
- Java基础知识 第一章 mySql配置 (一)
- 获取当天的开始和结束时间
- OpenCV实战笔记(2):格式转化
- KMP算法实现
- 在std::cin中按回车的意义探究
- LG 的数学计划 ---- 第三步 欧几里得算法和扩展欧几里得
- 我的第一篇博文
- Open GL ES 三角形绘制
- 《剑指offer》面试题66 矩阵中的路径
- JSP 注释
- 【数据结构与算法分析】《算法竞赛入门经典》第二章 示例及答案
- (27)HTML5-JQuery标签控制