UVA 455 – 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
如果一个字符串可以由某个长度为k的字符串重复多次得到,则称该串以k为周期。输入一个字符串输出最小周期。
 
  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. }  
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值