1 //====================================================
2 //迭代加深搜索求字符串最小周期;
3 //====================================================
4
5 #include <stdio.h>
6 #include <Windows.h>
7 #include <stdlib.h>
8
9 int main()
10 {
11 char *str;
12 int length=1;
13
14 //====================================================
15 //输入字符串str(char *)并计算长度length(int);
16 //====================================================
17 printf("请输入字符串:");
18 str = (char *)calloc(length, sizeof (char));
19
20 for (; (*(str + length - 1) = getchar()) != '\n'; ++length)
21 {
22 realloc(str, length + 1);
23 }
24 *(str + (--length)) = '\0';
25
26 //====================================================
27 //求出最小周期;
28 //====================================================
29 int i,j;
30 char *move;
31 //state=1时表示为可能的解,state=0时表示不可能的解;
32 int state = 0;
33
34 //找到正确的解则退出第一层循环;
35 for (i = 1; i <= (length / 2) && (state == 0); ++i)
36 {
37 if ((length % i) == 0)
38 {
39 state = 1;
40 move = str + i;
41 for (j = 0; (j < i) && (state == 1) && (*move != NULL); ++j,++move)
42 {
43 if (*(str + (j % i)) != *move)
44 {
45 state = 0;
46 }
47 }
48 }
49 }
50
51 //====================================================
52 //输出最小周期;
53 //====================================================
54 if (state == 1)
55 {
56 --i;
57 printf("最小周期为:\n");
58 for (j = 0; j < i; ++j)
59 {
60 printf("%c", *(str + j));
61 }
62 printf("\n");
63 }
64 else
65 {
66 printf("最小周期为:%s\n", str);
67 }
68
69 free(str);
70
71 system("pause>nul");
72 return 0;
73 }