本题链接:点击打开链接
本题题意:
本题是求第一个字符串中包含多少第二个字符串,即求子字符串个数。
解题思路:
本题可选用KMP算法,具体方法与hdu 1686 Oulipo相似。
参考代码:
#include<stdio.h>
#include<string.h>
#define MAX 1010
char str1[MAX],str2[MAX];
int next[MAX];
int len1,len2,cnt;
void getnext()
{
int i=0,j=-1;
next[0]=-1;
while(i<len2)
{
if(j==-1||str2[i]==str2[j])
{
i++;j++;
next[i]=j;
}
else
j=next[j];
}
}
void kmp()
{
int i=0,j=0;
while(i<len1)
{
if(j==-1||str1[i]==str2[j])
{
i++;j++;
if(j==len2)
cnt++;
}
else
j=next[j];
}
}
int main()
{
while(scanf("%s%s",str1,str2)!=EOF)
{
if(!strcmp(str1,"#"))
break;
cnt=0;
len1=strlen(str1);
len2=strlen(str2);
getnext();
kmp();
printf("%d\n",cnt);
}
return 0;
}