Periodic Strings(周期字符串)
作者:互联网
题目
A character string is said to have period k if it can be formed by concatenating one or more repetitions
of another string of length k. For example, the string ”abcabcabcabc” has period 3, since it is formed
by 4 repetitions of the string ”abc”. It also has periods 6 (two repetitions of ”abcabc”) and 12 (one
repetition of ”abcabcabcabc”).
Write a program to read a character string and determine its smallest period.
Input
The first line oif the input file will contain a single integer N indicating how many test case that your
program will test followed by a blank line. Each test case will contain a single character string of up
to 80 non-blank characters. Two consecutive input will separated by a blank line.
Output
An integer denoting the smallest period of the input string for each input. Two consecutive output are separated by a blank line.
Sample Input
1
HoHoHo
Sample Output
2
分析
这个题要求每组重复元素的个数,直接二重循环搜索即可,不过可以加一些条件加快搜索速度。
代码+注释
#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main()
{
int n;
string l;
cin>>n;
while(n--)
{
cin>>l;
int a=l.size(); //求出输入字符串的大小。
int flag=0;
for(int i=1;i<=a;i++) //第一重循环
{
if(a%i==0) //剪枝
{
for(flag=i;flag<a;flag++) //判断是否满足条件。
{
if(l[flag%i]!=l[flag]) //若不满足,flag=0,停止第二重循环。
{
flag=0;
break;
}
}
if(flag==0) //若不满足,搜索下一组。
{
continue;
}
else if(flag==a) //若满足,输出最小重复元素个数,停止第一重循环。
{
cout<<i<<endl;
break;
}
}
}
if(n!=0)cout<<endl;
}
return 0;
}
标签:string,int,period,will,Periodic,blank,字符串,input,Strings 来源: https://blog.csdn.net/weixin_43105110/article/details/88082067