455 - Periodic Strings(书上习题3-4)

我已经尽力了。。实在是不知道错在哪里。昨天下午开始弄的,现在还没解决 T.T。(目前为止卡最长的)

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<math.h>
 4 int main()
 5 {
 6     int n;
 7     int t;
 8     char s[81];
 9     scanf("%d",&n);
10 
11         while(n--)
12        {
13         scanf("%s",s);
14 
15         for(t=1; t<=strlen(s)/2; t++)
16         {
17                 int p;
18                 for( p=t; p<strlen(s); p++)
19                 {
20                     if(s[p]!=s[p%t])
21                     {
22                         break;
23                     }
24                 }
25                 if(p>=strlen(s))
26                 {
27                   printf("%d\n",t);
28                   break;
29                 }
30             }
31 
32         if(t>strlen(s)/2)
33         {
34             printf("%d\n",strlen(s));
35         }
36 
37          if(n)  printf("\n");
38 }
39     return 0;
40 }

 这道题纠结了差不多两天了吧。。反复改代码,改格式,后来还以为是人家题意没说清楚。。然而现在终于知道是什么错误了 :思路有漏洞,判断的是从第二个周期开始往后每个字符与第一个周期的那些字符比较,相同就过,比如 abcabcab这样的也就过了,错了,。改后如下,过了。

 

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<math.h>
 4 int main()
 5 {
 6     int n;
 7     int t;
 8     char s[81];
 9     scanf("%d",&n);
10     while(n--)
11     {
12         scanf("%s",s);
13         for(t=1; t<=strlen(s)/2; t++)
14         {
15             if(strlen(s)%t!=0)
16                 continue;
17             int p;
18             for( p=t; p<strlen(s); p++)
19             {
20                 if(s[p]!=s[p%t])
21                 {
22                     break;
23                 }
24             }
25             if(p>=strlen(s))
26             {
27                 printf("%d\n",t);
28                 break;
29             }
30 
31           }
32             if(t>strlen(s)/2)
33             {
34                 printf("%d\n",strlen(s));
35             }
36 
37             if(n)  printf("\n");
38 
39     }
40     return 0;
41 }

 

posted @ 2015-12-09 09:12  cherry_yue  阅读(49)  评论(0)    收藏  举报