LeetCode 28 实现strStr() 字符串匹配KMP

// N*M算法
// KMP算法,这里是学习刘汝佳大神书上的代码



class Solution {
    // public int strStr(String haystack, String needle){
    //     if (needle == null || needle.length() == 0)    return 0;
    //     if (haystack == null || haystack.length() == 0) return -1;
    //     if (haystack.length() < needle.length()) return -1;
    //     boolean flag = false;
    //     for (int i = 0;i < haystack.length() - needle.length() + 1; i++){
    //         flag = false;

    //         for (int j = 0, index = i; j < needle.length(); j++,index++){
    //             if (haystack.charAt(index) != needle.charAt(j)){
    //                 flag = true;
    //             }
    //         }
    //         if (!flag)
    //             return i;
    //     }
    //     return -1;
    // }

    public int strStr(String haystack, String needle){
        if (needle == null || needle.length() == 0)    return 0;
        if (haystack == null || haystack.length() == 0) return -1;
        if (haystack.length() < needle.length()) return -1;
        int[] f = new int[needle.length() + 1];
        getFail(needle, f);

        int n = haystack.length();
        int m = needle.length();
        int j = 0;
        for (int i = 0;i < n;i ++){
            while(j != 0 && haystack.charAt(i) != needle.charAt(j))
                j = f[j];
            
            if (haystack.charAt(i) == needle.charAt(j)) j++;
            if (j == m) return i - m + 1;
        }
        return -1;
    }

    public void getFail(String P, int[] f){
        int m = P.length();
        f[0] = 0;
        f[1] = 0;
        for (int i = 1; i < m; i++){
            int j = f[i];
            while (j != 0 && P.charAt(i) != P.charAt(j))
                j = f[j];
            f[i + 1] = P.charAt(i) == P.charAt(j) ? j + 1 : 0;
        }
    }
}

 

你可能感兴趣的:(LeetCode,Java)