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 <stdio.h>
#include <string.h>
const int N =  100000 + 10;
char s1[N],s2[N];
int next[N];
int len1,len2;
void getNext(){
    int i=1,j=0;
    next[1]=0;
    while(i<=len1){//优化后的next函数
        if(j==0||s2[i]==s2[j]){
            i++;j++;
            if(s2[i]!=s2[j]) next[i]=j;
            else next[i]=next[j];
        }
        else j=next[j];
    }
}


/*优化前的next函数
void getnext(){
int i = 1, j = 0;
next[1] = 0;
while(i <= len1){
if(j == 0 || s2[i] == s2[j]){
i++, j++;
next[i] = j;
}else{
j = next[j];
}
}
}*/
int kmp(){
    int i,j;
    int res=0;
    for(i=1,j=0; i<=len1; i++)
    {
        while(j>0&&s2[j+1]!=s1[i])
         j=next[j];
        if(s2[j+1] == s1[i])
            j= j + 1;
        if(j==len2)
        {
            res++;
            j=0;
        }
    }
    return res;
}
int main(){
    int i,j,res;
    while(gets(s2+1)){
        gets(s1+1);
        len1=strlen(s1+1);
        len2=strlen(s2+1);
        getNext();
        printf("%d\n",kmp());
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值