KMP算法:
void getNext(const string& needle,int next[])
{
const int n = needle.size();
int i = 0;
int j = -1;
next[i] = j;
while (i < n)
{
if (j == -1 || needle[i] == needle[j])
{
++i;
++j;
next[i] = j;
}
else
{
j = next[j];
}
}
}
int kmp(const string& hay, const string& needle)
{
const int n = hay.size();
const int m = needle.size();
int* next = new int[m];
getNext(needle, next);
int i = 0;
int j = 0;
while (i < n&&j < m)
{
if (hay[i] == needle[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
//delete next;
if (j == m)
return i - j;
else
return -1;
}