【Leetcode】之Implement strStr()
2015-11-23 09:59
295 查看
一.问题描述
Implement strStr().Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
二.我的解题思路
这道题目也比较简单,使用简单的双指针比较即可。注意为了提高时间效率,在程序的开头可以对两个字符串的length先进行一个初步的比较。测试通过的程序如下所示:class Solution { public: int strStr(string haystack, string needle) { int len=haystack.length();int candidate=-1; int need = 0;int ned_len=needle.length(); if(len<ned_len) return -1; if(len==ned_len) { for(int i=0;i<len;i++){ if(haystack[i]!=needle[i]) return -1; } return 0; } if(len==0 || ned_len==0) return 0; for(int i=0;i<len;i++){ if(haystack[i]==needle[need]){ candidate=i; while( i<len && need<ned_len){ if(haystack[i]!=needle[need]) break; else {i++;need++;} } if(need==ned_len && (haystack[i-1]==needle[need-1])) return candidate; else { need=0; i=candidate; candidate=-1; } } } return candidate; } };
相关文章推荐
- redis
- js prototype
- 图片碎片效果
- 解决Windows下运行php Composer出现SSL报错的问题
- Http协议三次握手过程
- Unity3D 自定义 Editor 扩展
- MYSQL 编程之重连篇
- 使用Flexible实现手淘H5页面的终端适配
- stm32波特率计算
- C mysql
- Weblogic在Linux下启动特别慢及进入控制台慢的解决方法
- Kali下安装Wiznote
- 2D旋转和3D旋转
- java生成pdf文档
- 14.2.5 InnoDB Undo Logs
- Java自定义注解和运行时靠反射获取注解
- 异常语句
- Linux统计文件行数
- 我装的win10,怎么装不了 Intel HAXM模拟加速器呢
- 14.2.4 InnoDB Redo Log