UVa-455 - Periodic Strings:simple

本文介绍了一种通过遍历字符串长度的因子来查找字符串周期性的方法。利用C++ STL中的string类的substr()函数,该算法能够高效地检测出字符串是否具有重复的模式,并找出最短的重复单元长度。

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

这里用到了STL中string求子串方法的sub_str()

然后就是按照字符串长度的因子从小到一个个比较了

sub_str用法如下(贴来的)

string substr(int start=0,int count= -1);
从起始位置开始复制字符串中的count 个字符,并返回这些字符作为子串。
如果字符串尾部小于count字符或者count 为-1,则字符串尾停止复制。
如果不使用参数调用只包括位置start,则substr()返回从位置开始到字符串尾部的子串。

#include <cstring>
#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

int main()
{
	string s;
	int T;
	cin>>T;
	for(int t=0;t<T;t++){
        if(t)
            cout<<endl;
        int flag=0;
        cin>>s;

        for(int factor=1;factor<=s.length();factor++){
                if((s.length()%factor)==0){

                    string s1=s.substr(0,factor),s2;

                    for(int i=factor;i<s.length();i+=factor)
                    {
                        s2=s.substr(i,factor);

                        if(s2!=s1){
                            flag=1;
                            break;
                        }
                    }
                    if(flag==0){
                        cout<<factor<<endl;
                        break;
                    }
                    else
                        flag=0;
                }//if s.length
        }//factor
	}//T--
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值