KMP算法实现
#include<iostream>
#include<string>
using namespace std;
void GetNext(string s, int* next)
{
int len = s.length();
int j = 0, k = -1;
next[0] = -1;
while (j < len)
{
if (k == -1 || s[k] == s[j])
{
k++;
j++;
if (s[k] != s[j])
{
next[j] = k;
}
else
{
next[j] = next[k];
}
}
else
{
k = next[k];
}
}
}
int main()
{
string s1, s2;
while (cin >> s1 >> s2)
{
int next[10009];
int lena = s1.length();
int lenb = s2.length();
GetNext(s2, next);
int i = 0, j = 0;
int ans = 0;
while (i < lena)
{
if (j == -1 || s1[i] == s2[j])
{
i++;
j++;
}
else
{
j = next[j];
}
if (j == lenb)
{
cout << i - j + 1 << " ";
ans++;
j = next[j];
}
}
cout << endl << ans << endl;
}
return 0;
}