public static int KMP(String s1,String s2){
if(s1.length()<s2.length()||null==s2||s2.length()==0) return -1;
//求模式串的next数组
int[] next=new int[s2.length()];
next[0] = 0;
int j = 0;int i = 1;
while(i<s2.length()){
if(s2.charAt(i)==s2.charAt(j)){
next[i] = j+1;
i++;
j++;
}else{
if(j>0){
j = next[j-1];
}else{
next[i] = 0;
i++;
}
}
}
for(int a=0,b=0;a<s1.length();){
if(s1.charAt(a)==s2.charAt(b)){
if(b==s2.length()-1){
return a-s2.length()+1;
}
a++;b++;
}else{
if(b>0){
b = next[b-1];
}else{
b = 0;
a++;
}
}
}
return -1;
}
附: