Implement strStr() leetcode
2015-10-21 00:08
274 查看
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a
解题:我用的方法相当于暴力破解:int strStr(string haystack, string needle) ;
首先,遍历haystack,依次寻找第一个与needle第一个字符匹配的位置,同时记录相对于该位置的下一个位置(我记为ret,一旦接下来的匹配不成功,重新遍历haystack时,就从ret开始),如果遍历完haystack都没匹配成功,则返回-1。注意边界条件!!
我的源代码如下:
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a
char *or
String, please click the reload button to reset your code definition.
解题:我用的方法相当于暴力破解:int strStr(string haystack, string needle) ;
首先,遍历haystack,依次寻找第一个与needle第一个字符匹配的位置,同时记录相对于该位置的下一个位置(我记为ret,一旦接下来的匹配不成功,重新遍历haystack时,就从ret开始),如果遍历完haystack都没匹配成功,则返回-1。注意边界条件!!
我的源代码如下:
class Solution { public: int strStr(string haystack, string needle) { if(needle.empty()) return 0; if (haystack.empty()) { if(!needle.empty()) return -1; } if(needle.size()>haystack.size()) return -1; int index = 0, reset = -1; while (index < haystack.size()) { if (haystack[index] != needle[0]) { index++; continue; } reset = index + 1; int i; for ( i = 1;index+needle.size()<=haystack.size()&& i < needle.size(); ++i) { if (haystack[index + i] != needle[i]) break; } if (i == needle.size()) return index ; else index = reset; } return -1; } };
相关文章推荐
- 链表给定节点删除
- 关于layoutSubviews以及drawRect方法
- LeetCode6:ZigZag Conversion
- NYOJ 37 回文字符串
- 推荐的讲解算法的网站、好博客:
- cc.game对象和游戏启动流程
- 利用CountDownTimer实现倒计时功能
- c# 之 New新知
- PHP中字符串转换为数值 可能会遇到的坑
- MyBatis整合Spring
- hdu 1664如此爽的一道bfs+数论
- 在软件部署中使用 strace 进行调试
- 在 Linux 上用 strace 来理解系统调用
- Apache PDFBox 2.0.0 RC1 发布下载
- Linux执行.sh文件时提示No such file or directory该怎么办(三种解决办法)
- Linux中rz命令和sz命令使用详解大全
- JSP下载服务器文件的方法
- JSP导出Excel文件的方法
- JSP实现远程文件下载保存到服务器指定目录中的方法
- Linux正则表达式特性详解及BRE与ERE的异同点