leetcode笔记:Implement strStr()
2015-10-09 23:40
375 查看
一.题目描述
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
二.题目分析
实现strstr()函数。返回needle(关键字)在haystack(字符串)中第一次出现的位置,如果needle不在haystack中,则返回-1。由于使用暴力方法的时间复杂度为O(mn)会超时,可使用著名的KMP算法解决。该是由Knuth,Morris,Pratt共同提出的字符串匹配算法,其对于任何字符串和目标字符串,都可以在线性时间内完成匹配查找,是一个非常优秀的字符串匹配算法。
三.示例代码
KMP算法:
四.小结
对于这题,还有其他一些有名的算法,如Rabin-Karp和Boyer-Moore算法。
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
二.题目分析
实现strstr()函数。返回needle(关键字)在haystack(字符串)中第一次出现的位置,如果needle不在haystack中,则返回-1。由于使用暴力方法的时间复杂度为O(mn)会超时,可使用著名的KMP算法解决。该是由Knuth,Morris,Pratt共同提出的字符串匹配算法,其对于任何字符串和目标字符串,都可以在线性时间内完成匹配查找,是一个非常优秀的字符串匹配算法。
三.示例代码
KMP算法:
class Solution { public: void getNext(vector<int> &next, string &needle) { int i = 0, j = -1; next[i] = j; while (i != needle.length()) { while (j != -1 && needle[i] != needle[j]) j = next[j]; next[++i] = ++j; } } int strStr(string haystack, string needle) { if (haystack.empty()) return needle.empty() ? 0 : -1; if (needle.empty()) return 0; vector<int> next(needle.length() + 1); getNext(next, needle); int i = 0, j = 0; while (i != haystack.length()) { while (j != -1 && haystack[i] != needle[j]) j = next[j]; ++i; ++j; if (j == needle.length()) return i - j; } return -1; } };
四.小结
对于这题,还有其他一些有名的算法,如Rabin-Karp和Boyer-Moore算法。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android之获取手机上的图片和视频缩略图thumbnails
- android string.xml文件中的整型和string型代替
- Android java 与 javascript互访(相互调用)的方法例子
- 关于指针的一些事情
- 数据库链接字符串查询网站
- android上改变listView的选中颜色
- String.intern
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Prototype源码浅析 String部分(二)
- Flex字符串比较 还有Flex字符串操作
- Ruby中的String对象学习笔记
- Ruby中创建字符串的一些技巧小结
- ASP下经常用的字符串等函数参考资料
- 将字符串小写转大写并延时输出的批处理代码
- 将字符串转换成System.Drawing.Color类型的方法
- Lua中调用C++函数示例
- Lua源码中字符串类型的实现
- Lua性能优化技巧(四):关于字符串