28.实现strStr()
- 不用string类的函数
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
双指针
- 一个指针遍历haystack字符串,一个指针遍历needle,如果第二个指针遍历完就是存在,不存在注意返回第一个指针的位置。
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.size()==0) return 0;
else if(haystack.size()==0) return -1;
int i=0,j=0;
while(i<haystack.size() && j<needle.size()){
if(haystack[i]==needle[j]){
i++;
j++;
}
else{
i=i-j+1;
j=0;
}
}
if(j==needle.size()) return i-needle.size();
return -1;
}
};
通过时间: