一.问题描述
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;
}
};

本文介绍如何实现strStr()函数,用于在主字符串中查找子字符串的首次出现位置。通过双指针法,提高了时间效率。详细解释了程序逻辑,并附上测试通过的代码。
1186

被折叠的 条评论
为什么被折叠?



