[LeetCode]Implement strStr()
2015-07-22 21:24
423 查看
对KMP算法的一个很好的说明:KMP算法详解
下面是对算法的实现,有几点需要留意:
1,边界条件:needle的长度不能大于haystack
2,前条件:计算next数组,next的index代表字符串的长度;p 为haystack索引,q为needle索引。
3,循环结束条件,haystack和needle有一个遍历结束;
4,不变式:如果haystack[p] == needle[q], p++, q++; 否则,如果q>0, 则q = next[q]; 如果q == 0 , 则p++(q都已经指向needle第一个了还是不相等,只有p指向haystack的下一位了)
5,返回值:如果haystack没有被遍历完,说明needle遍历匹配完全;
如果haystack遍历完了,分两种情况;1,needle也遍历完,说明匹配;2,needle没有遍历完,没匹配。
方法二:两次循环足矣
下面是对算法的实现,有几点需要留意:
1,边界条件:needle的长度不能大于haystack
2,前条件:计算next数组,next的index代表字符串的长度;p 为haystack索引,q为needle索引。
3,循环结束条件,haystack和needle有一个遍历结束;
4,不变式:如果haystack[p] == needle[q], p++, q++; 否则,如果q>0, 则q = next[q]; 如果q == 0 , 则p++(q都已经指向needle第一个了还是不相等,只有p指向haystack的下一位了)
5,返回值:如果haystack没有被遍历完,说明needle遍历匹配完全;
如果haystack遍历完了,分两种情况;1,needle也遍历完,说明匹配;2,needle没有遍历完,没匹配。
class Solution { public: int strStr(string haystack, string needle) { if (haystack.length() < needle.length()){ return -1; } vector<int> next; next.push_back(0); next.push_back(0); //get next array int j = 0; for (int i = 1; i < needle.length(); ++i){ // j 在每次循环开始,都表示next[i]的值,同时也表示需要比较的下一个位置 while( j > 0 && needle[i] != needle[j]) j = next[j]; if (needle[i] == needle[j]) j++; next.push_back(j); } // match int p = 0; // haystack index int q = 0; // needle index while(p < haystack.length() && q < needle.length()){ if (haystack[p] != needle[q]){ if ( q > 0){ q = next[q]; }else{ p++; } }else{ p++; q++; } } if ( p < haystack.length()){ return p - needle.length(); } if (q >= needle.length() && haystack[p-1] == needle[q-1]){ return p - needle.length(); } return -1; } };
方法二:两次循环足矣
// java public class Solution { public int strStr(String haystack, String needle) { for (int i = 0; ; i++){ for (int j = 0; ; j++){ if (j == needle.length()) return i; if (i + j == haystack.length()) return -1; if (needle.charAt(j) != haystack.charAt(i+j)) break; } } } }
相关文章推荐
- seajs模块化jQuery与jQuery插件
- 自己写的UnitY实用小工具或脚本——AR阴影以及Mask遮挡
- hdu 5289 Assignment(2015多校第一场第2题)RMQ+二分(或者multiset模拟过程)
- qsort 模板
- Vim笔记
- PHP常用函数
- 深入理解JAVA虚拟机笔记 - 03
- lua打印调用堆栈
- DNA poj2440
- js怎样判断对象是否是空对象
- mysql 之 SQL 语句复习
- Plus One
- OpenID和OAuth的区别及第三方登录的安全隐患分析
- 关于双击.py文件闪退的问题
- matlab GPU 操作
- RequireJs 深入理解
- [机器学习&数据挖掘]SVM---核函数
- 《慕客网:IOS基础入门之Foundation框架初体验》学习笔记 <四> NSMutableArray
- nfs、samba、squid代理部署及优化
- loading条顺滑加载