HDU - 3746 Cyclic Nacklace 【KMP模板 求字符串循环节个数【最大/最小循环节的个数

8 篇文章 0 订阅

求最循环节的个数:

#include "iostream"
#include "algorithm"
#include "cstring"
#include "cstdio"
#include "iomanip"
using namespace std;
string  a;
int nextt[100005];

void getnext(){
    int i=0,j=-1;
    nextt[0]=-1;
    while(i<a.length()){
        if(j==-1||a[i]==a[j]){
            i++;
            j++;
            nextt[i]=j;
        }
        else
            j=nextt[j];
    }
}

int main(){
    std::ios::sync_with_stdio(false);
    int T,n,m;
    cin>>T;
    while(T--){
        cin>>a;
        getnext();
        int n=a.length()-nextt[a.length()];//循环节长度
        int m=a.length();
        if(n!=m&&m%n==0)printf("0\n");//如果可以多次循环
        else printf("%d\n",n-nextt[m]%n);//取余的作用:abcab,去掉abc
    }
    return 0;
}

 

附:求最大的循环节的个数

int ans = 1;
int l=s.length();
if(l%(l-nextt[l])==0)
      ans=l/(l-nextt[l]);
cout<<ans<<endl;

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值