D.截取方案数 | |||||
| |||||
Description | |||||
给定一个模式串T,主串S,问:从S中截取T有多少种方案? | |||||
Input | |||||
有多组测试数据,对于每组测试数据,第一行是模式串T,第二行是主串S,数据中仅包含大小写字母和数字,模式串T长度不超过10^4, 主串S长度不超过10^5。 注意:数据是随机的。 | |||||
Output | |||||
对于每组测试数据,输出一行,为截取方案数。 | |||||
Sample Input | |||||
abc
abcdaabcab
abcd
abcdaabcab
aba
abababa
| |||||
Sample Output | |||||
2
1
3
|
#include<cstdio>
#include<cstring>
char a[100005],b[100005];
int next[100005],n,m;
void getnext()
{
int i=0,j=-1;
next[0]=-1;
while(b[i])
{
if(j==-1 || b[i]==b[j])
{
next[++i]=++j;
}
else
j=next[j];
}
}
int kmp()
{
int i=0,j=0,tot=0;
while(i<n)
{
if(j==-1 || a[i]==b[j])
{
i++;
j++;
}
else
j=next[j];
if(j==m) tot++;
}
return tot;
}
int main()
{
int t,i;
while(scanf("%s",b)!=EOF)
{
scanf("%s",a);
m=strlen(b);
n=strlen(a);
memset(next,0,sizeof(next));
getnext();
printf("%d\n",kmp());
}
return 0;
}
结果:
77790 | D | Accepted | G++ | 110ms | 1476k | 797B | 2014-03-15 15:38:15 |