KMP算法----java实现
字符串的模式匹配本文先实现最基本的回溯实现的已经KMP算法,BM算法后面博文继续实现。ps:本篇博文强烈参考了July大神的作品,地址http://blog.csdn.net/v_july_v/article/details/6545192.再次感激大神~~
1.最基本的回溯实现字符串模式匹配
package com.sheepmu; public class KMPText { public static void main(String[] args) { String s0="abcdeabckkfgh"; String s1="abck"; char[] as0=s0.toCharArray(); char[] as1=s1.toCharArray(); System.out.println(getIndex(as0,as1)); } public static int getIndex(char[] as0,char[] as1) { int len0=as0.length; int len1=as1.length; int i=0,j=0; while(i<len0&&j<len1) { if(as0[i]==as1[j]) { i++; j++; } else { i=i-j+1; j=0; } } if(j>=len1) { return i-j; } return -1; } }
2.KMP算法实现字符串模式匹配
package com.sheepmu; public class KMPText { public static void main(String[] args) { String s0="abcdeabckkfgh"; String s1="abcke"; char[] as0=s0.toCharArray(); char[] as1=s1.toCharArray(); System.out.println(getKMP(as0,as1)); } public static int[] next(char[] as1) { int[] next=new int[as1.length]; next[0]=-1; int len1=as1.length; int i=0,j=-1; while(i<len1-1)//!!!!!!!!!!!!!记得-1 { if(j==-1||as1[i]==as1[j]) { i++; j++; if(as1[i]!=as1[j]) { next[i]=j; } else { next[i]=next[j]; } } else { j=next[j]; } } return next; } public static int getKMP(char[] as0,char[] as1) { int len0=as0.length; int len1=as1.length; int i=0,j=0; int[] next=next(as1); while(i<len0&&j<len1) { if(j==-1||as0[i]==as1[j]) { i++; j++; } else { j=next[j]; } } if(j>=len1) { return i-j; } return -1; } }