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
思路: 暴力枚舉循環節長度,循環問題用求模運算
//#define LOCAL/*注意提交時將此行代碼註釋掉*/
//#include<windows.h>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int fun(char *str)
{
int k,len=strlen(str);
for(int i=1;i<=strlen(str);i++)
{//i是循序節長度
int flag=1;
if(len%i==0)
{
for(k=i;k<len;k++)
{
if(str[k]!=str[k%i])//循環用求模運算 使得後面的字符與最初的循環體進行比較
{
flag=0;
break;
}
}
if(flag)
return i;
}
}
return len;
}
int main()
{
//讀寫文件代碼寫在這裏不會影響計時函數
#ifdef LOCAL
freopen( "input.txt", "r", stdin );
freopen( "output.txt", "w", stdout );
#endif // LOCAL
/*計時函數*/
#ifdef LOCAL
DWORD start_time, end_time;
start_time = GetTickCount();
#endif // LOCAL
/*main函數主體*/
int N;
int flag=0;
cin >> N;
//getchar();
char str[100];
while(N--)
{
cin >> str;
cout << fun(str) << endl;
if(N)
cout<<endl;
}
#ifdef LOCAL
end_time = GetTickCount();
//提交時將時間函數輸出註釋掉
cout << "Running time is: " << static_cast<double>( end_time - start_time ) * 1.0 / 1000 << "ms" << endl; //輸出運行時間
#endif // LOCAL
return 0;
}