来源 :https://www.cnblogs.com/c-cloud/p/3224788.html
class Solution {
public:
int strStr(string haystack, string needle)
{
if (needle.size() == 0)
return 0;
vector<int> next(needle.size(), 0);
getNext(needle, next);
for (int i = 0, j = 0; i < haystack.size();i++)
{
while ( j > 0 && haystack[i] != needle[j])
j = next[j - 1];
if (haystack[i] == needle[j])
j++;
if(j == needle.size())
return (i + 1 - needle.size());
}
return -1;
}
private:
void getNext(string& s, vector<int>& next);
};
inline void Solution::getNext(string& s, vector<int>& next)
{
for (int i = 1, k = 0; i < s.size(); ++i)
{
while(k > 0 && s[i] != s[k])
{
k = next[k - 1];
}
if (s[i] == s[k])
k++;
next[i] = k;
}
return;
}