KMP算法

时间:2019-06-06 19:05:36   收藏:0   阅读:97

KMP基本思路很简单,关键在于求失配数组,也就是next数组

next[k]表示[0, k]的最长前缀后缀的索引(不包括p[0, k])
假设我们现在有了p[0,i-1]的最长前缀后缀索引为k,如何求p[0, i]的最长前缀后缀呢?

class Solution {
private:
    vector<int> next;
    void ComputeNext(const string& p){
        int n = p.size();
        next.resize(n);
        
        int k = -1;
        next[0] = k;
        for(int i = 1; i < n; i++){
            while(k > -1 && p[k+1] != p[i]){
                k = next[k];
            }
            
            if(p[k+1] == p[i]) k++;
            next[i] = k;
        }
    }
    
    
    int KMP(const string &t, const string &p){
        ComputeNext(p);
        int k = -1;
        for(int i = 0; i < t.size(); i++){
            while(k > -1 && p[k+1] != t[i]){
                k = next[k];
            }
            
            if(p[k+1] == t[i]) k++;
            if(k == p.size() - 1) return i - p.size() + 1;
        }
        
        return -1;
    }
public:
    int strStr(string haystack, string needle) {
        return needle == "" ? 0 : KMP(haystack, needle);
    }
};

原文:https://www.cnblogs.com/qbits/p/10986489.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!