实现 strStr()
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
思路与代码
这题比较简单,用的也是很常规的方法,注意haystack长度小于needle的情况,还有needle为空的情况就可以了
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.size()==0){
return 0;
}
if(haystack.size()<needle.size()){
return -1;
}
int res=-1;
for(int i=0;i<haystack.size()-needle.size()+1;i++){
if(haystack[i]==needle[0]){
res=i;
if(haystack.substr(i,needle.size())==needle){
return res;
}
}
res=-1;
}
return res;
}
};