实现 strStr()(简单)
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例
解题
用两个for循环进行遍历查找即可
class Solution {
public:
int strStr(string haystack, string needle) {
if(needle.empty()) return 0;
int m=haystack.size(),n=needle.size();
if(m<n) return -1;
for(int i=0;i<=m-n;++i){
int j=0;
for(j=0;j<n;++j){
if(haystack[i+j]!=needle[j])
break;
}
if(j==n) return i;
}
return -1;
}
};
也可以写的更加简洁一些,开头直接套两个 for 循环,不写终止条件,然后判断假如j到达 needle 的末尾了,此时返回i;若此时 i+j 到达 haystack 的长度了,返回 -1;否则若当前对应的字符不匹配,直接跳出当前循环,参见代码如下:
class Solution {
public:
int strStr(string haystack, string needle) {
for (int i = 0; ; ++i) {
for (int j = 0; ; ++j) {
if (j == needle.size()) return i;
if (i + j == haystack.size()) return -1;
if (needle[j] != haystack[i + j]) break;
}
}
return -1;
}
};