[Algorithms] KMP
2015-06-19 15:25
381 查看
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.
KMP on jBoxer's blog;
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.
KMP on jBoxer's blog;
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.
class Solution { public: int strStr(string haystack, string needle) { int m = needle.length(), n = haystack.length(); if (!m) return 0; vector<int> lps = kmpProcess(needle); for (int i = 0, j = 0; i < n; ) { if (needle[j] == haystack[i]) { i++; j++; } if (j == m) return i - j; if (i < n && needle[j] != haystack[i]) { if (j) j = lps[j - 1]; else i++; } } return -1; } private: vector<int> kmpProcess(string needle) { int m = needle.length(); vector<int> lps(m, 0); for (int i = 1, len = 0; i < m; ) { if (needle[i] == needle[len]) lps[i++] = ++len; else if (len) len = lps[len - 1]; else lps[i++] = 0; } return lps; } };
相关文章推荐
- com.google.gson.internal.LinkedTreeMap cannot be cast to test.UserBean at t..
- ubuntn上安装google chrome浏览器
- POJ1003-hangOver
- 百度site语法升级:官方logo可在多处展示
- Google Chrome 调试
- 【测测这是什么】——google地址
- Go语言学习示例
- [Machine Learning & Algorithm] 随机森林(Random Forest)
- 可访问的google的ip地址
- golang的跨域
- 关于windows下django使用celery实现异步调用(RabbitMQ)
- golang chan 发送接收测试数据
- 列表下拉/上拉刷新: (一)EGORefreshTableHeaderView使用、定义EGORefreshTableFooterView
- 【Mongous】write after end
- GO GO GO
- 《Gogoing》Alpha版会议总结
- Basic Sorting Algorithms
- Google Play来华 象征意义+跳板而已
- [翻译] NSDate-TimeAgo
- google host 2015-6-18