poj3461kmp

求模式串在原串出现次数。

 

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <climits>
#include <string>
#include <iostream>
#include <map>
#include <cstdlib>
#include <list>
#include <set>
#include <queue>
#include <stack>

using namespace std;

const int maxn=1111111;

int next[maxn];

void getnext(char *s)
{
    int len=strlen(s);
    int j=-1;int i=0;
    next[0]=-1;
    while(i<len){
        if(j==-1||s[i]==s[j]){
            i++;j++;next[i]=j;
        }
        else{
            j=next[j];
        }
    }
}//求next 数组函数   next[j]  表示从 str[j-1]向前和从头str[0]向后 最长相同串的长度
int ans;
void solve(char *s,char  *s1)
{
    int j=0;
    int len=strlen(s);int len1=strlen(s1);
    for(int i=0;i<len1;i++){
        if(j>0&&s1[i]!=s[j]) j= next[j]; //失配之后 将 str[next[j]] 与 str1[i] 比较
        if(s[j]==s1[i]) j++;
        if(j==len){
            ans++;
            j=next[j];  //找到答案 后继续失配。。
        }
    }
    cout<<ans<<endl;
}
char str[maxn];char str1[maxn];
int main()
{
    int Icase;
    cin>>Icase;
    while(Icase--){
        scanf("%s",str);scanf("%s",str1);
        ans=0;
        getnext(str);
        solve(str,str1);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/yigexigua/p/3870170.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值