[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 };

 

目录
相关文章
|
机器学习/深度学习 算法 TensorFlow
维特比算法(Viterbi algorithm)
维特比算法(Viterbi algorithm)是一种用于解码隐马尔可夫模型(Hidden Markov Model,HMM)的动态规划算法。它用于找到给定观测序列条件下的最有可能的隐藏状态序列。
543 1
|
算法
大话 KMP 算法
大话 KMP 算法
65 1
|
6月前
|
算法 Python
KMP
【7月更文挑战第7天】
52 5
|
8月前
|
算法
算法学习--KMP与Trie
算法学习--KMP与Trie
|
机器学习/深度学习 存储 缓存
Lecture 3:动态规划
Lecture 3:动态规划
127 1
|
索引
KMP Implement
KMP Implement
57 0
|
存储 算法 搜索推荐
KMP 算法(Knuth-Morris-Pratt)
KMP算法,全称为Knuth-Morris-Pratt算法,是一种字符串匹配算法。它的基本思想是,当出现字符串不匹配时,可以知道一部分文本内容是一定匹配的,可以利用这些信息避免重新匹配已经匹配过的文本。这种算法的时间复杂度为O(n+m),其中n是文本串的长度,m是模式串的长度,比暴力匹配算法具有更高的效率。KMP算法的核心是利用模式串本身的特点,预处理出一个next数组,用于在匹配过程中快速移动模式串。
668 0
KMP 算法(Knuth-Morris-Pratt)
|
存储 算法
理解KMP
理解KMP
83 0
|
Windows
German Collegiate Programming Contest 2019 H . Historical Maths (二分 大数)
German Collegiate Programming Contest 2019 H . Historical Maths (二分 大数)
95 0
German Collegiate Programming Contest 2019 H . Historical Maths (二分 大数)

热门文章

最新文章

下一篇
开通oss服务