class Solution {
public int strStr(String haystack, String needle) {
if(needle.length()>haystack.length())
return -1;
if(needle.length()==0)
return 0;
char[] hs=haystack.toCharArray();
char[] ne=needle.toCharArray();
int[] next=new int[ne.length];
next[0]=-1;int j=0,k=-1;
while(j<needle.length()-1){
if(k==-1||ne[k]==ne[j]){
next[++j]=++k;
}else{
k=next[k];
}
}
int i=0,head;
while(i<=(haystack.length()-needle.length())){
head=i;
int m=0;
for(m=0;m<needle.length();m++){
if(ne[m]!=hs[i]){
i=head+(m-next[m]);
break;
}
i++;
}
if(m==needle.length()){
return head;
}
}
return -1;
}
}