P - 剪花布条
题目描述:
一块花布条,里面有些图案,另有一块直接可用的小饰条,里面也有一些图案。对于给定的花布条和小饰条,计算一下能从花布条中尽可能剪出几块小饰条来呢?
Input
输入中含有一些数据,分别是成对出现的花布条和小饰条,其布条都是用可见ASCII字符表示的,可见的ASCII字符有多少个,布条的花纹也有多少种花样。花纹条和小饰条不会超过1000个字符长。如果遇见#字符,则不再进行工作。
Output
输出能从花纹布中剪出的最多小饰条个数,如果一块都没有,那就老老实实输出0,每个结果之间应换行。
Sample Input
abcde a3
aaaaaa aa
#
Sample Output
0
3
分析:熟悉了KMP,一眼就能看出这又是一个KMP匹配题。不过在匹配的时候有一点点小的差异。具体见代码
#include"stdio.h"
#include"string.h"
void Get_next(char text[],int next[])
{
int i,j;
int len=strlen(text);
next[0]=-1;
i=0;j=-1;
while(i<len)
{
if(j==-1||text[i]==text[j])
{
i++;j++;
if(text[i]==text[j])
next[i]=next[j];
else
next[i]=j;
}
else
j=next[j];
}
}
int Index_KMP(char text[],int next[],char word[])
{
int i,j,k;
int lentext=strlen(text);
int lenword=strlen(word);
int count=0;
i=0;j=0;
while(i<lentext)
{
while(j<lenword&&i<lentext)
{
if(j==-1||text[i]==word[j])
{
i++;j++;
}
else
{
j=next[j];
}
if(j==lenword)//这里是匹配成功了
{
count++;//数量加1
j=0;//重新从0开始匹配,因为i并未到达尽头
}
}
}
return count;
}
int main()
{
char text[1001],word[1001];
int next[1001];
int i,j,count;
while(~scanf("%s",text))
{
if(text[0]=='#')
break;
scanf("%s",word);
Get_next(word,next);
count=Index_KMP(text,next,word);
printf("%d\n",count);
}
}
还没有评论,来说两句吧...