剪花布条
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 21303 Accepted Submission(s): 13313
abcde a3 aaaaaa aa #
0 3
思路:这题需要对KMP的匹配有一定的理解,只要匹配完了之后再从模板串的开头从新匹配就行了。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAX_N 1005
using namespace std;
char t[MAX_N],p[MAX_N];
int ne[MAX_N];
void makeNext(const char p[],int ne[])
{
int len=strlen(p);
ne[0]=0;
for(int i=1,k=0;i<len;i++)
{
while(k>0&&p[i]!=p[k]) k=ne[k-1];
if(p[i]==p[k]) k++;
ne[i]=k;
}
}
int kmp(const char t[],const char p[],int ne[])
{
int n=strlen(t),m=strlen(p),ans=0;
makeNext(p,ne);
for(int i=0,k=0;i<n;i++)
{
while(k>0&&t[i]!=p[k]) k=ne[k-1];
if(t[i]==p[k]) k++;
if(k==m)
{
ans++;
k=0;
}
}
return ans;
}
int main()
{
while(~scanf("%s",t))
{
if(t[0]=='#') break;
scanf("%s",p);
printf("%d\n",kmp(t,p,ne));
}
return 0;
}
626



被折叠的 条评论
为什么被折叠?



