Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size();
int m = needle.size();
if(needle.empty())
return 0;
for(int i= 0, j = 0; i < n && j < m ; ++i)
{
if(haystack[i] == needle[j])
{
if(j == m-1)
return i-j;
else
++j;
}
else{
i -= j;
j = 0;
}
}
return -1;
}
};
class Solution {
public:
int strStr(string haystack, string needle) {
return haystack.find(needle);
}
};
本文提供了两种实现strStr()函数的方法:一种是手动遍历比较,另一种是使用C++标准库中的find方法。这两种方法都能返回子串在主串中首次出现的位置索引。
204

被折叠的 条评论
为什么被折叠?



