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
1 #include<bits/stdc++.h> 2 #define maxn 10005 3 using namespace std; 4 int n; 5 int main() 6 { 7 scanf("%d",&n); 8 getchar(); 9 for(int ii=1;ii<=n;ii++) 10 { 11 char a[100]; 12 getchar(); 13 scanf("%s",a); 14 int len=strlen(a); 15 int flag=0; 16 for(int i=1;i<=len;i++) 17 { 18 flag=0; 19 if((len%i)==0) 20 {for(int j=i;j<len;j++) 21 if(a[j]!=a[j%i]) 22 { 23 flag=1;break; 24 } 25 } 26 else flag=1; 27 if(!flag) 28 {printf("%d",i); 29 break;} 30 } 31 if(ii==n)printf(" "); 32 else 33 printf(" "); 34 } 35 return 0; 36 }
思路:
周期可能是[1,len]从小到大遍历所有可能,当可能是正确的,跳出循环。
如果字符串的长度是周期的倍数,该周期可能成立,否则一定是错的。
在上述成立的条件下,如果字符串的每一位,a[j]==a[j%i];则该周期成立。
注意点:
一开始没判断if((len%i)==0)。所以比如遇到这样的情况我一开始的代码会wa:abcabca