KMP

作者: Michaelwen003 | 来源:发表于2018-07-08 00:59 被阅读0次
   public int strStr(String haystack, String needle) {
    if(needle == null ||needle.length()==0)return 0;
    if(haystack == null ||haystack.length()==0)return -1;
    int[] next = makeInt(needle);
    int j=0;
    int i=0;
    while(j<needle.length()&&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];
        }
    }
    
    if(j==needle.length())return i-j;
    return -1;
}
private int[] makeInt(String needle){
    int[] next = new int[needle.length()+1];
    next[0]=-1;
    int j=-1;
    int i=0;
    while(i<needle.length()){
        if(j==-1 || needle.charAt(i)==needle.charAt(j)){
            i++;
            j++;
            next[i]=j;
        }else {
            j = next[j];
        }
    }
    return next;
}

相关文章

网友评论

      本文标题:KMP

      本文链接:https://www.haomeiwen.com/subject/bxmnuftx.html