kmp模板

97 阅读1分钟
class Solution {
    public int strStr(String haystack, String needle) {
        int hLen=haystack.length();
        int nLen=needle.length();
        if(nLen==0) return 0;
        int[] next=new int[nLen];
        char[] h=haystack.toCharArray();
        char[] n=needle.toCharArray();
        for(int i=1,j=0;i<nLen;i++){
            while(j>0 && n[j]!=n[i])
                j=next[j-1];
            if(n[i]==n[j]) j++;
            next[i]=j;
        }
        for(int i=0,j=0;i<hLen;i++){
            while(j>0 && h[i]!=n[j])
                j=next[j-1];
            if(h[i]==n[j]) j++;
            if(j==nLen) return i-nLen+1;
        }
        return -1;
    }
}