KMP。和之前那道HDU1686 Oulipo很像。区别是,这个不允许重复出现。即aaaaaa 模式串为aa。输出的结果为3,而那道Oulipo是5.
两道都可以当模板来用~
HDU 1686 Oulipo代码:HDU 1686 Oulipo
本题AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char a[1005],b[1005];
int nextt[2000];
void getnextt(char *b)
{
int l=strlen(b);
int i=0,j=-1;
nextt[0]=-1;
while(i<l)
{
if(j==-1||b[i]==b[j])
{
i++;
j++;
nextt[i]=j;
}
else
j=nextt[j];
}
}
int main()
{
while(scanf("%s",a))
{
if(a[0]=='#'&&a[1]=='\0')
break;
scanf("%s",b);
getnextt(b);
int sum=0;
int l1=strlen(a);
int l2=strlen(b);
if(l2>l1)
printf("0\n");
else
{
int i=0,j=0;
while(i<l1)
{
if(j==-1||a[i]==b[j])
{
i++;
j++;
}
else
j=nextt[j];
if(j==l2)
{
j=0;
sum++;
}
}
printf("%d\n",sum);
}
}
return 0;
}
如果对KMP不是很理解,这里有KMP的详解和学习资料: KMP及KMP next数组详解&KMP课件