2021-02-03

uva455

如果想要判断一个子字符串是否是最小周期的那个字符串,必须要全部遍历一遍才会知道;

所以可以用字符串的首尾相连,即(i+j)%n,一个一个判断;

另一个思路是,可以先截取字符串前n个,将这前n个加到截取剩下的字符串末尾,然后与原串比较是否相同,如果相同,则说明这个字符串的长度就是最小周期;(substr函数)

#include <bits/stdc++.h>
using namespace std;
int main()
{
    char str[100];
    int N;
    cin >> N;
    while (N--)
    {
        cin >> str;
        int len = strlen(str), t = 1;
        while (1)
        {
            int c = 0;//
            for (int i = 0; i < len; ++i)
                if (str[i] == str[(i + t) % len]) c++;//如果字符串有一个匹配的,那么就延续到下一个,知道n个都匹配;
                else break;
            if (c == len) break;//只要不是n个都匹配,那么周期就不是它;
            t++;
        }
        cout << t << endl;
        if (N != 0) cout << endl;
    }
    return 0;
}


#include<bits/stdc++.h >
using namespace std;
int main()
{

    int t;
    cin>>t;
    while(t--)
    {

        string a;
        cin>>a;

        int period=1;
        int n=a.length();
        while(1)
        {
            int flags=0;
            for(int i=0; i<n; i++)
            {
                if(a[i]!=a[(i+period)%n])
                {
                    flags=1;
                     period++;
                    break;

                }
            }
            if(flags==0){//flags用来做标志;
                cout<<period<<endl;
                break;
            }

        }
    }
}

但其实,因为是周期性的,所以,周期字符串的长度一定会是n的倍数,这样的话会减少一定的时间;

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值