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到字符串的长度一个一个枚举即可,判断第l[j]是否跟在它前面i位的字符相等,由于在她前面i位上的字符跟l[j%i]相等,所以判断跟l[j%i]是否相等即可
代码:
#include<stdio.h>
#include<string.h>
int n,i,j,len;
int main(void)
{
scanf("%d",&n);
while(n--)
{
char l[100];
scanf("%s",l);
len=strlen(l);
for(i=1;i<=len;i++)
{
if(len%i==0)//这里进行剪枝,子序列的长度一定能被序列长度整除
{
for(j=i;j<len;j++)
{
if(l[j]!=l[j%i])//这句话的意思就是l[j]位上是否等于在它前i位上的字符
break;
}
if(j==len)
{
printf("%d\n",i);
break;
}
}
}
if(n)
printf("\n");
}
return 0;
}