UVA 455 – Periodic Strings

来源:互联网 发布:女王级战列舰 知乎 编辑:程序博客网 时间:2024/06/06 07:08

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

1HoHoHo

Sample Output

2
如果一个字符串可以由某个长度为k的字符串重复多次得到,则称该串以k为周期。输入一个字符串输出最小周期。
[cpp] view plain copy
  1. #include <iostream>  
  2. using namespace std;  
  3. int compare(string s,int a,int b)  
  4. {  
  5. if(s.length()%(b-a)!=0) return 0;//如果不满足周期串的要求,还未比较完字符串就已经结束。比如:abcdabcdabc、aabaa  
  6. for(int i=1;i<s.length()-b;i++)  
  7.     {     if(s[a+i]!=s[b+i])//一旦有不相等的字符出现,返回假  
  8.     return 0;  
  9.     }  
  10.     return 1;  
  11. }  
  12. int main(){  
  13. int T;  
  14. int flag=0;  
  15. cin>>T;  
  16. while(T--)  
  17. {string s;  
  18. cin>>s;  
  19. int res=0;  
  20. for(int i=1;i<s.length();i++)  
  21. {  
  22. if(s[0]==s[i]) {if(res=compare(s,0,i)) { if(flag) cout<<endl;  
  23.     flag=1;    cout<<i<<endl; break;}    }  
  24. }  
  25. if(!res) {if(flag) cout<<endl; cout<<s.length()<<endl;  
  26.     flag=1; }  
  27. }  
  28. return 0;  
  29. }  
0 0
原创粉丝点击