KMP匹配原串中有多少子串

本文介绍了一个基于字符串匹配的算法实现,通过KMP算法的核心思想来完成模式串在目标串中的查找,并结合特定条件生成字符串。文章详细展示了如何利用C语言进行编程实现,包括初始化变量、输入参数处理、字符串生成及KMP匹配过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<string>
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
char str[1000010];
char s[1000010];
int nextt[1000010];
int len2;
void get_next()
{
    nextt[0]=-1;
    int i=0,j=-1;
    while(i<len2)
    {
        if(j==-1|s[i]==s[j])
        {
            i++,j++;
            nextt[i]=j;
        }
        else
            j=nextt[j];
    }
}
int main()
{
    int n,a,b,l,r;
    scanf("%d%d%d%d%d",&n,&a,&b,&l,&r);
    scanf("%s",s);
    len2=strlen(s);
    int w,cnt=0;
    for(int i=1;i<=n;i++)
    {
        if(i==1)
        {
            w=b;
            if(w>=l&&w<=r&&w%2==0)str[cnt++]='A';
            else if(w>=l&&w<=r&&w%2==1)str[cnt++]='T';
            else if((w<l||w>r)&&w%2==0)str[cnt++]='G';
            else if((w<l||w>r)&&w%2==1)str[cnt++]='C';
        }
        else
        {
            w=(w+a)%n;
            if(w>=l&&w<=r&&w%2==0) str[cnt++]='A';
            else if(w>=l&&w<=r&&w%2==1)str[cnt++]='T';
            else if((w<l||w>r)&&w%2==0)str[cnt++]='G';
            else if((w<l||w>r)&&w%2==1)str[cnt++]='C';
        }
    }
    str[cnt]='\0';
    get_next();
    int j=0,sum=0,i=0;
    //printf("%s\n",str);
    while(i<n)
    {
        if(str[i]==s[j])
        {
            j++,i++;
            if(j==len2)
            {
                sum++;
            }
        }
        else if(nextt[j]==-1)//把这种情况分出来,让j重新匹配
            i++;
        else
        {
            j=nextt[j];
        }
    }
    printf("%d\n",sum);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值