zoukankan      html  css  js  c++  java
  • KMP算法

    KMP算法

    KMP算法是一种改进的字符串匹配算法,由D.E.Knuth、J.H.Morris和V.R.Pratt提出的(简称KMP算法)。

    KMP算法的核心是利用匹配失败后的信息,尽量减少模式串与主串的匹配次数以达到快速匹配的目的。具体实现就是通过一个next()函数实现,函数本身包含了模式串的局部匹配信息。KMP算法的时间复杂度O(m+n)。

    KMP模式匹配算法主要用于字符串的匹配,大大可以减少重复遍历的情况

    算法原理

    KMP实现代码C++

    void GetNext(string needle, vector<int> &next)
    {
        for (int i = 1, k = 0; i < needle.size(); ++i) {
            while (k && needle[k] != needle[i]) 
                k = next[k - 1];
            if (needle[k] == needle[i]) 
                ++k;
            next[i] = k;
        }
    }
    
    int IndexKMP(string haystack, string needle) {
        if (needle.empty()) 
            return 0;
    
        vector<int> next(needle.size(), 0);
        GetNext(needle, next);
        for (int i = 0, k = 0; i < haystack.size(); ++i) {
            while (k && needle[k] != haystack[i]) 
                k = next[k - 1];
            if (needle[k] == haystack[i]) 
                ++k;
            if (k == needle.size()) 
                return i - k + 1;
        }
    
        return -1;
    }
    
  • 相关阅读:
    P4005 小 Y 和地铁
    P1039 侦探推理
    P2766 最长不下降子序列问题
    P2312 解方程
    P2169 正则表达式
    UOJ#22. 【UR #1】外星人
    UOJ#21. 【UR #1】缩进优化
    Palindromeness CodeChef
    bzoj5392 [Lydsy1806月赛]路径统计
    997D Cycles in product
  • 原文地址:https://www.cnblogs.com/zou107/p/13885692.html
Copyright © 2011-2022 走看看