您的位置:首页 > 其它

【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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: