第一次学会KMP算法,纪念一下

视频1:

https://www.bilibili.com/video/av11866460?from=search&seid=5536761404371030698

视频2:

https://www.bilibili.com/video/av16828557/?spm_id_from=333.788.videocard.0

代码

class Solution {
    // haystack -> source
    // needle -> target
    public int strStr(String haystack, String needle) {
        if(needle == null) return -1;
        if(haystack == null) return -1;
        if(needle.length() == 0 && haystack != null) return 0;
        if(haystack.length() == 0) return -1;
        char[] text = haystack.toCharArray();
        char[] pattern = needle.toCharArray();
        int n = text.length;
        int m = pattern.length;
        int[] prefix = new int[m];
        prefix_table(pattern, prefix, m);
        move_prefix_table(prefix, m);
        return kmp_search(text, pattern, prefix, n, m);
    }
    public void prefix_table(char[] pattern, int[] prefix, int m){
        prefix[0] = 0;
        int len = 0;
        int i = 1;
        while(i < m){
            if(pattern[len] == pattern[i]){
                len++;
                prefix[i] = len;
                i++;
            }
            else{
                if(len > 0) len = prefix[len - 1];
                else{
                    prefix[i] = len;
                    i++;
                }
            }
        }
    }
    public void move_prefix_table(int[] prefix, int m){
        int i;
        for(i = m - 1; i > 0; i--)
            prefix[i] = prefix[i - 1];
        prefix[0] = -1;
    }
    public int kmp_search(char[] text, char[] pattern, int[] prefix, int n, int m){
        int i = 0; // text 
        int j = 0; // pattern
        while(i < n){
            if(j == m - 1 && text[i] == pattern[j]) 
                return i - m + 1;
            if(text[i] == pattern[j]){
                i++;
                j++;
            }
            else{
                j = prefix[j];
                if(j == -1){
                    i++;
                    j++;
                }
            }
        }
        return -1;
    }
}

 

你可能感兴趣的:(数据结构算法)