strstr实现(练习KMP算法的好例子)
2015-09-10 16:45
232 查看
solution 1.暴力破解
solution 2: KMP变形
<span style="font-size:18px;">class Solution { public: int strStr(string haystack, string needle) { int m = haystack.size(); int n = needle.size(); for(int i = 0; i <= m-n; i ++) { int j; for(j = 0; j < n; j ++) { if(haystack[i+j] != needle[j]) break; } if(j == n) return i; } return -1; } }; </span>
solution 2: KMP变形
class Solution { public: int strStr(char *haystack, char *needle) { int hlen = strlen(haystack); int nlen = strlen(needle); int* next = new int[nlen]; getNext(needle, next); int i = 0; int j = 0; while(i < hlen && j < nlen) { if(j == -1 || haystack[i] == needle[j]) {// match current position, go next i ++; j ++; } else {// jump to the previous position to try matching j = next[j]; } } if(j == nlen) // all match return i-nlen; else return -1; } void getNext(char *needle, int next[]) {// self match to contruct next array int nlen = strlen(needle); int j = -1; // slow pointer int i = 0; // fast pointer next[i] = -1; //init next has one element while(i < nlen-1) { if(j == -1 || needle[i] == needle[j]) { j ++; i ++; //thus the condition (i < nlen-1) next[i] = j; //if position i not match, jump to position j } else { j = next[j]; //jump to the previous position to try matching } } } };
相关文章推荐
- js 40 个技巧
- 【LeetCode】206. Reverse Linked List
- Visual Studio VS2010统计代码行数
- 为Cordova + Ionic + AngularJS 应用添加微信分享功能
- BAE(疑惑)
- HTML-CSS
- 2015多校联合第二场hdu5303Delicious Apples DP 类似最长山峰序列
- 学习Java 23种设计模式详解笔记之行为型模式(三)
- 商户入网第三方支付——支付接口
- 0909我对操作系统的认识
- uva 1513 - Movie collection--树状数组--预留前n个位置
- android 调用相机拍照 伪闪退
- C++ explicit
- 如何截获并替换系统最小化功能
- 个人学习笔记---软中断(下半部)和软件中断(系统调用)的区别
- springmvc checkboxes 回显问题
- 热备,冷备,云备的区别
- SPDY 是什么?如何部署 SPDY?
- 一段代码 完全解读 SharedPreferedces。
- 避免引用Context造成的内存泄露