28. Implement strStr()
2016-05-16 00:29
357 查看
1.Question
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
2.Code
a. 字符串string的比较可以直接用 == 。也可以是.campare。
b. 针对这个问题有个更高效的知名算法, 称为KMP算法(看毛片算法),思想大致明白了,但是实现不容易。有时间可以了解 下如何代码实现。
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
2.Code
class Solution { public: int strStr(string haystack, string needle) { int sizeofneedle = needle.size(); for(int i = 0, size = haystack.size() - needle.size() + 1; i < size; i++) { if(haystack.substr(i, sizeofneedle) == needle) return i; } return -1; } };3.Note
a. 字符串string的比较可以直接用 == 。也可以是.campare。
b. 针对这个问题有个更高效的知名算法, 称为KMP算法(看毛片算法),思想大致明白了,但是实现不容易。有时间可以了解 下如何代码实现。
相关文章推荐
- Ubuntu 下载 & 编译 Android5.1 源码
- 适合代码展示的字体 [收集]
- form表单select联动
- Linux下php安装Redis扩展
- 应用服务器知识(1)--JBoss
- JAVA vim 开发环境配置
- 6.分析Linux内核创建一个新进程的过程
- epoll总结
- Entity Framework 6 Recipes 2nd Edition(13-5)译 -> 使POCO的修改追踪更高
- python urllib, urllib2实现登陆和简单爬取网页(个人坑点笔记)
- linux编译安装Nginx1.6.0+MySQL5.6.19+PHP5.5.14
- hdu 5682 zxa and leaf (二分+搜索)
- 2016"百度之星" - 资格赛(Astar Round1) 1004()
- Swift-下标脚本和继承(Subscripts and Inheritance)(十一)
- Python笔记
- 2016"百度之星" - 资格赛(Astar Round1)Problem A(乘法逆元)
- Entity Framework 6 Recipes 2nd Edition(13-6)译 -> 自动编译的LINQ查询
- ThreadPoolExecutor机制
- ImageView的属性android:scaleType作用
- crond介绍