hdu3746(KMP:next数组应用)

26 篇文章 0 订阅
9 篇文章 0 订阅

题意:一个字符串,要求只能在字符串左右两侧添加的字符,将字符串变成最少循环2次的周期串。

题意:问:需要添加多少个字符

KMP:next数组的应用

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
#define N 100010

char s[N];
int nextval[N];
int len;

void getnext(const char*s){
    int i=0,j=-1;
    nextval[0]=-1;
    while(i!=len){
        if(j==-1||s[i]==s[j]) nextval[++i]=++j;
        else j=nextval[j];
    }//while
}
int main(){
    int T;
    int length,ans;
    scanf("%d",&T);
    while(T--){
        scanf("%s",s);
        len=strlen(s);
        getnext(s);

        length = len-nextval[len];//最小循环周期
        if(len!=length&&len%length==0) printf("0\n");//长度为最小循环周期的倍数
        else{
            ans=length-nextval[len]%length;
            printf("%d\n",ans);
        }//else
    }//while
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值