[Algorithms] KMP

简介: KMP is a classic and yet notoriously hard-to-understand algorithm. However, I think the following two links give nice explanations.

KMP is a classic and yet notoriously hard-to-understand algorithm. However, I think the following two links give nice explanations. You may refer to them.

  1. KMP on jBoxer's blog;
  2. KMP on geeksforgeeks, with a well-commented C code.

I am sorry that I am still inable to give a personal explanation of the algorithm. I only read it from the two links above and mimic the code in the second link.

You may use this code to solve the problem Implement strStr() on LeetCode. My accepted 4ms C++ code using KMP is as follows.

 1 class Solution {
 2 public:
 3     int strStr(string haystack, string needle) {
 4         int m = needle.length(), n = haystack.length();
 5         if (!m) return 0;
 6         vector<int> lps = kmpProcess(needle);
 7         for (int i = 0, j = 0; i < n; ) {
 8             if (needle[j] == haystack[i]) {
 9                 i++;
10                 j++;
11             }
12             if (j == m) return i - j;
13             if (i < n && needle[j] != haystack[i]) {
14                 if (j) j = lps[j - 1];
15                 else i++;
16             }
17         }
18         return -1;
19     }
20 private:
21     vector<int> kmpProcess(string needle) {
22         int m = needle.length();
23         vector<int> lps(m, 0);
24         for (int i = 1, len = 0; i < m; ) {
25             if (needle[i] == needle[len])
26                 lps[i++] = ++len;
27             else if (len) len = lps[len - 1];
28             else lps[i++] = 0;
29         }
30         return lps;
31     }
32 };

 

目录
相关文章
|
算法
大话 KMP 算法
大话 KMP 算法
57 1
|
6月前
|
算法
|
算法 搜索推荐 安全
Boyer-Moore 字符串匹配算法
Boyer-Moore 字符串匹配算法
227 1
Boyer-Moore 字符串匹配算法
|
索引
KMP Implement
KMP Implement
54 0
|
存储 算法 搜索推荐
KMP 算法(Knuth-Morris-Pratt)
KMP算法,全称为Knuth-Morris-Pratt算法,是一种字符串匹配算法。它的基本思想是,当出现字符串不匹配时,可以知道一部分文本内容是一定匹配的,可以利用这些信息避免重新匹配已经匹配过的文本。这种算法的时间复杂度为O(n+m),其中n是文本串的长度,m是模式串的长度,比暴力匹配算法具有更高的效率。KMP算法的核心是利用模式串本身的特点,预处理出一个next数组,用于在匹配过程中快速移动模式串。
655 0
KMP 算法(Knuth-Morris-Pratt)
|
Windows
German Collegiate Programming Contest 2019 H . Historical Maths (二分 大数)
German Collegiate Programming Contest 2019 H . Historical Maths (二分 大数)
85 0
German Collegiate Programming Contest 2019 H . Historical Maths (二分 大数)
|
算法
KMP 算法的理解
KMP 算法的理解关于字符串的子串模式匹配算法,最经典最简单的的算法是BP算法(Brude-Force)。
98 0
KMP 算法的理解
UCF 2021 Practice F.Balanced Strings (思维 组合数学)
UCF 2021 Practice F.Balanced Strings (思维 组合数学)
105 0
|
算法 索引
KMP Algorithm 字符串匹配算法KMP小结
这篇小结主要是参考这篇帖子从头到尾彻底理解KMP,不得不佩服原作者,写的真是太详尽了,让博主产生了一种读学术论文的错觉。后来发现原作者是写书的,不由得更加敬佩了。博主不才,尝试着简化一些原帖子的内容,希望能更通俗易懂一些。
1637 0