关键是求解NEXT数组 Next数组就是当前字符之前的字符串中,有多大长度的相同前缀与后缀
public class KMP {
/**
* KMP算法的实现
*/
/**
* 求解NEXT数组
*/
private static void getNext(char [] p,int [] next){
int len = p.length;
next[0]= -1;
int k = -1;
int j =0;
while(j<len-1){
if(k==-1 || p[j]==p[k]){
++j;
++k;
if(p[j]!=p[k]){
next[j] =k;
}else{
next[j]=next[k];
}
}else{
k=next[k];
}
}
}
public static int KmpSearch(char [] s,char [] p){
int i=0;
int j =0;
int [] next = new int[p.length];
getNext(p, next);
int SLen = s.length;
int PLen = p.length;
while(i<SLen && j<PLen){
if(j ==-1|| s[i] == p[j]){
i++;
j++;
}else{
j = next[j];
}
}
if( j ==PLen){
return i-j;
}else{
return -1;
}
}
public static void main(String[] args) {
int index = KmpSearch("ADBDGSDFGSD".toCharArray(), "DGS".toCharArray());
System.out.println(index);
}
}