时间复杂度:O(N)
C++代码:
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty())
return 0;
auto it_h = haystack.begin(), it_h2 = it_h, it_n = needle.begin();
while (it_h != haystack.end())
{
it_h2 = it_h, it_n = needle.begin();
int count = 0;
while (it_n != needle.end())
{
if (*it_n != *it_h2)
break;
count++;
it_h2++;
it_n++;
}
if (count == needle.length())
return it_h - haystack.begin();
it_h++;
}
return -1;
}
};