题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2087
#include <stdio.h>
#include <string.h>
#define MAXN 1002
int next[MAXN],len1,len2;
char text[MAXN],pattern[MAXN];
void getNext()
{
int i=0,j=-1;
next[0]=-1;
while(i<len2)
{
if (j==-1||pattern[i]==pattern[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int KMP()
{
int i,j,count=0;
i=j=0;
getNext();
while(i<len1)
{
if(j==-1||text[i]==pattern[j])
{
i++;
j++;
if(j==len2)
{
count++;
j=0;//匹配成功,j要重新初始化0
}
}
else
j=next[j];
}
return count;
}
int main()
{
int ans;
while ( scanf("%s",text))
{
if(!strcmp(text,"#"))
break;
scanf("%s",pattern);
len1=strlen(text);
len2=strlen(pattern);
ans=KMP();
printf("%d\n",ans);
}
return 0;
}