poj 3461 Oulipo(KMP)

【题目大意】:给出一个字符串和一个文本串,求字符串子文本串中出现的次数。


【解题思路】:kmp模版加+一个累加变量 

     if (j==sn)
        {sum++;
         j=next[j-1];}

     当在文本串中匹配到字符串时,则进行累加即可。


【代码】:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <string>
#include <cctype>
#include <map>
#include <iomanip>
                   
using namespace std;
                   
#define eps 1e-8
#define pi acos(-1.0)
#define inf 1<<30
#define pb push_back
#define lc(x) (x << 1)
#define rc(x) (x << 1 | 1)
#define lowbit(x) (x & (-x))
#define ll long long

char s[10010],s1[1000010];
int next[10010];
int temp,sn,sn1,n;

int solve_kmp(){
    int j=0,sum=0;
    sn1=strlen(s1);
    for (int i=0; i<sn1; i++){
        while (j>0 && s1[i]!=s[j])
            j=next[j-1];
        if (s1[i]==s[j])
            j++;
        else j=0;
        if (j==sn){
            sum++;
            j=next[j-1];
        }
    }
    return sum; 
}
void solve_kmp_next(){ 
    next[0]=0;
    next[1]=0;
    sn=strlen(s);
    for(int i=1; i<sn; i++){
        temp=next[i-1];
        while(temp && s[temp]!=s[i])
            temp=next[temp-1];
        if(s[temp]==s[i])
            next[i]=temp+1;
        else    next[i]=0;
    }     
}

int main(){ 
    cin >> n;
    for (int i=1; i<=n; i++){
        scanf("%s",&s);
        getchar();
        scanf("%s",&s1);
        solve_kmp_next();
        cout << solve_kmp() <<endl;
    }
    return 0;   
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值