题目描述:
给定一个haystack字符串和一个needle字符串,在haystack字符串中找出needle字符串出现的第一个位置(从0开始)。如果不存在,则返回-1.
解析:
【1】直接采用库函数的方法
class Solution {
public:
int strStr(string haystack, string needle) {
return haystack.find(needle);
}
};
【2】采用暴力方法:
class Solution {
public:
int strStr(string haystack, string needle) {
int i=0,j=0;
while(i<haystack.size()&&j<needle.size()){ //遍历字符串
if(haystack[i]==needle[j]) i++,j++; //相等时,指针都+1
else i=i-j+1,j=0; //不相等时,i从下个指针开始匹配,j从0开始
}
if(j==needle.size()) return i-j; //返回出现重复字符串开始位置
return -1;
}
};