[Algorithms] KMP

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值