Leetcode28 Java实现
代码实现(kmp)
class Solution {
public int strStr(String haystack, String needle) {
if(needle.length()<1){
return 0;
}
char[] ha = haystack.toCharArray();
char[] ne = needle.toCharArray();
int hi=0;
int ni = 0;
int [] next = getNextArray(ne);
while(hi<ha.length&&ni<ne.length){
if(ha[hi]==ne[ni]){
hi++;
ni++;
}else{ if(next[ni]==-1){
hi++;
}else{
ni=next[ni];
}
}
}
return ni==ne.length? hi-ni:-1;
}
public static int [] getNextArray(char[] a){
if(a.length==1){
return new int[] {-1};
}
int []next = new int[a.length];
next[0] = -1;
next[1] = 0;
int i = 2;
int j = 0;
while(i<next.length){
if(a[i-1]==a[j]){
next[i++]=++j;
}else if(j>0){
j=next[j];
}else{
next[i++]=0;
}
}
return next;
}
}