这是一道KMP的水题,还没明白KMP是怎么回事 ==,先贴了代码,明天继续研究。
#include <stdio.h>
#include <string.h>
const int MaxN = 1000010;
char word[MaxN/10], txt[MaxN];
int next[MaxN/10];
void KMP_next(char b[], int pre[])
{
int n = (int)strlen(b), k;
pre[0] = -1; k = -1;
for(int i = 1; i < n; i++)
{
while(k > -1 && b[k+1] != b[i]) k = pre[k];
if(b[k+1] == b[i]) k++;
pre[i] = k;
}
}
int main()
{
int n;
for(scanf("%d%*c", &n); n--;)
{
gets(word); gets(txt);
KMP_next(word, next);
int cnt = 0, len = (int)strlen(word);
for(int i = 0, j = -1; txt[i]; ++i)
{
while(j > -1 && word[j+1] != txt[i])
j = next[j];
if(word[j+1] == txt[i])
j++;
if(j == len-1) {
cnt++; j = next[j];
}
}
printf("%d\n", cnt);
}
return 0;
}