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
AC code:
#include<stdio.h> #include<string.h> int main() { char a[128]; int n,i,k,d; scanf("%d",&n); while (n--) { scanf("%s",a); d = strlen(a); for (i = 1 ; i <= d ; i++) if (d%i == 0) { for (k = i ; k < d; k++) if (a[k] != a[k%i]) break; if (k == d) { printf("%d\n",i); break; } } if (n) printf("\n"); } return 0; }个人认为这道题坑还是比较多的,思路一开始还是不正确。时隔6天之后又重新思考,终于过了。初始思路就是copy字符到一个新的字符串发现这样会让asa这样的数据也成立,后来改来改去还是不正确,那就剩下改思路了。用下标取余,好方法!
本文介绍了一种通过取余操作高效判断字符串最小周期的方法,并提供了一个C语言实现的示例程序。该程序能够读取一系列字符串并输出每个字符串的最小周期。
1076

被折叠的 条评论
为什么被折叠?



