KMP算法
来源:互联网 发布:xshell连接linux 编辑:程序博客网 时间:2024/06/06 15:46
在长度为M字符串S1中找到长度为N字符串S2的匹配位置,没有找到返回-1。
使用KMP算法可以在O(M+N)时间复杂度完成。
import java.lang.reflect.Array;import java.util.ArrayList;import java.util.Arrays;import java.util.Scanner;public class Main { public static void main(String[] args) { Scanner scan=new Scanner(System.in); while(scan.hasNext()){ String s1=scan.next(); String s2=scan.next(); System.out.println(getIndex(s1,s2)); } } public static int getIndex(String s1,String s2){//kmp算法 char[]ch1=s1.toCharArray(); char[]ch2=s2.toCharArray(); int[]next=getNext(ch2); int si=0; int mi=0; while(si<ch1.length&&mi<ch2.length){ if(ch1[si]==ch2[mi]){ si++; mi++; }else if(next[mi]==-1){ si++; }else{ mi=next[mi]; } } return mi<ch2.length?-1:si-ch2.length; } public static int[] getNext(char[] ch){ if(ch.length==1){ return new int[]{-1}; } int[]next=new int[ch.length]; next[0]=-1; next[1]=0; int pos=2; int cn=0; while(pos<next.length){ if(ch[pos-1]==ch[cn]){ next[pos++]=cn+1; }else if(cn>0){ cn=next[cn]; }else{ next[pos++]=0; } } 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算法
- 剑指offer_数组---把数组排成最小的数
- Python学习(十三)——pandas函数库2
- Symmetric Tree
- 千寻穗C语言学习笔记 8.25 8.26(伪)
- 关于puppet脚本的一些笔记
- KMP算法
- Listener(监听器)
- 作用域public,protected,private的区别?以及不写时的区别?
- 一张图理清SpringMVC工作原理
- HDFS对象存储:Ozone的块异步删除服务
- AWS
- Linux下刷x210开发板
- 八月,即将结束
- nachos操作系统-基于优先级的线程调度