首页 > 其他 > 详细

Count and Say

时间:2015-04-10 22:19:22      阅读:221      评论:0      收藏:0      [点我收藏+]

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

 

一开始理解错题意,认为是给定一个整数,输出它的“读&说”形式,代码如下:

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         string str = int2string(n);
 5         int len = str.length();
 6         if(len == 0) return NULL;
 7         if(len == 1) return str;
 8         
 9         string result;
10         int count = 1;
11         for(int i = 1; i < len; i++){
12             if(str[i-1] == str[i]) count++;
13             else{
14                 result = result + int2string(count) + str[i-1];
15                 count = 1;
16             }
17             if(i == len - 1) result = result + int2string(count) + str[i];
18         }
19         return result;
20     }
21     string int2string(int n){
22         string s;
23         while(n){
24             s += n % 10 + 0;
25             n /= 10;
26         }
27         reverse(s.begin(), s.end());
28         return s;
29     }
30 };

然后老是不通过,翻了别人的解题思路,才知道是什么意思 0.0

题目意思为  第一个序列为1;由于1已经表示为1了,所以第二个序列为Count-And-Say第一个序列的结果,为11;同理第三个序列为Count-And-Say第二个序列的结果,为21;第四个序列为1211……

代码如下:

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         if(n == 1) return "1";
 5         string result = "1";
 6         for(int i = 1; i < n; i++){
 7             result = convert(result);
 8         }
 9         return result;
10     }
11     string convert(string str){
12          int len = str.length();
13          if(len == 1) return "1" + str;
14          string result;
15          int count = 1;
16          for(int i = 1; i < len; i++){
17              if(str[i-1] == str[i]) count++;
18              else{
19                  result = result + static_cast<char>(count + 0) + str[i-1];
20                  count = 1;
21              }
22              if(i == len - 1) result = result + static_cast<char>(count + 0) + str[i];
23          }
24          return result;
25     }
26 };

 

Count and Say

原文:http://www.cnblogs.com/amazingzoe/p/4415770.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!