http://blog.csdn.net/starstar1992/article/details/54913261
public class Test{ public static void main(String[] args){ String s1="abababd"; String s2="abd"; System.out.println(kmp(s1,s2)); } public static void getNext(String s,int[] next){ int len=s.length(); next[0]=-1; int k=-1; for(int i=1;i<len;i++){ while(k!=-1 && s.charAt(k+1)!=s.charAt(i)){ k=next[k]; } if(s.charAt(k+1)!=s.charAt(i)){ k++; } next[i]=k; } } public static int kmp(String str,String subStr){ int[] next=new int[subStr.length()]; getNext(subStr,next); int k=-1; int len=str.length(); for(int i=0;i<len;i++){ while(k!=-1 && str.charAt(i)!=subStr.charAt(k+1)){ k=next[k]; } if(str.charAt(i)==subStr.charAt(k+1)){ k++; } if(k==subStr.length()-1){ return i-subStr.length()+1; } } return -1; } }