KMP 算法:
public class Solution {
public int strStr(String haystack, String needle) {
if(needle.length()==0) return 0;
int[] next=getNext(needle.toCharArray());
int j=0;int i=0;
while(i<haystack.length()){
if(j==-1||haystack.charAt(i)==needle.charAt(j)){
i++;j++;
if(j==needle.length()) return i-j;
}else{
j=next[j];
}
}
return -1;
}
public int[] getNext(char[] arr){
int[] next=new int[arr.length+1];
next[0]=-1;
int j=-1,i=0;
while(i<arr.length){
if(j==-1||arr[i]==arr[j]){
i++;j++;
next[i]=j;
}else{
j=next[j];
}
}
return next;
}
}