http://acm.hdu.edu.cn/showproblem.php?pid=2087
还是对于next函数的运用,注意再找到之后要把j赋值为0,而不是next[j]
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
using namespace std;
int next[1005];
char st[10005],sp[1005];
void getnext(char *p)
{
int i,j;
i=0;
j=-1;
next[0]=-1;
int len=strlen(p);
while(i<len)
{
if(j==-1||p[i]==p[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
int kmp(char *s,char *p)
{
int len1=strlen(s);
int len2=strlen(p);
int i,j,n;
i=j=n=0;
while(i<len1&&j<len2)
{
if(j==-1||s[i]==p[j])
{
i++;
j++;
if(j==len2)
{
n++;
j=0;
}
}
else
j=next[j];
}
return n;
}
int main()
{
while(scanf("%s",st)!=EOF)
{
int i,j;
int len1=strlen(st);
if(len1==1&&st[0]=='#')
break;
scanf("%s",sp);
int len2=strlen(sp);
getnext(sp);
printf("%d\n",kmp(st,sp));
}
}