本题就是经典的模式串匹配问题,只需要对上文中的程序稍作修改即可。(hihoCoder上的KMP算法一题,与本题一模一样)
#include <stdio.h>
#include <string.h>
void getNext(char t[], int next[])
{
int i=0, j=-1, tLen=strlen(t);
next[i]=j;
while (i<tLen)
if (j==-1 || t[i]==t[j])
{
i++;j++;
if (t[i]!=t[j]) next[i]=j; else next[i]=next[j];
}
else j=next[j];
}
int kmpMain(char s[], char t[], int next[], int pos)
{
int i=pos, j=0, sLen=strlen(s), tLen=strlen(t),total=0;
while (i<sLen)
{
if (j==-1 || s[i]==t[j]){i++; j++;}
else j=next[j];
if (j==tLen) {total++; j=next[j];} //修改的地方
}
return total;
}
int main()
{
char w[10001],t[1000001];
int n,i,next[10001];
scanf("%d",&n);
for (i=0;i<n;i++)
{
scanf("%s",w);
scanf("%s",t);
getNext(w,next);
printf("%d\n",kmpMain(t,w,next,0));
}
return 0;
}