题目要求:实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
分析:一种方法可以使用string 函数中find()函数,还有就是使用暴力方法,去遍历整个字符串!
方法一:
//使用库函数:string中的find函数!
int strStr(string haystack, string needle) {
if(haystack.empty() && !needle.empty())
return -1;
if(needle.empty())
return 0;
if(haystack.size() < needle.size())
return -1;
int pos;
pos = haystack.find(needle);
return pos;
}
方法二:
使用暴力方法时候,应该注意匹配几个字符,最后没有完全匹配的情况,索引应该回退到 i = i - j + 1 .
//BF方法:
int strStr(string haystack, string needle) {
if(haystack.empty() && !needle.empty())
return -1;
if(needle.empty())
return 0;
if(haystack.size() < needle.size())
return -1;
int i=0,j=0;
while(haystack[i] != '\0' && needle[j] != '\0') {
if(haystack[i] == needle[j]) {
i++;
j++;
}
else {
i = i-j+1; //这里应该注意!!!
j=0;
}
}
if(needle[j] == '\0')
return i-j;
return -1;
}