首页 > 其他 > 详细

LeetCode OJ:Count and Say(数数)

时间:2015-10-21 00:20:41      阅读:258      评论: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就是1,2前面是1就是1一个(11),3前面2个1就是(21),然后是(1211),再是(111221)以此类推。。。 当时题目看了半天没看懂,又去别的地方查了下题目是什么意思才知道了:

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         string curr = "";
 5         if(n <= 0) return curr;
 6         curr = "1";
 7         for(int i = 1; i < n; ++i){
 8             curr = convert(curr);
 9         }
10         return curr;
11     }
12 
13     string convert(const string & prev){
14         //string result = "";
15         stringstream result;
16         char last = prev[0];
17         int count = 0;
18         int sz = prev.size();
19         for(int i = 0; i <= sz; ++i){//注意是<=
20             if(prev[i] == last)
21                 count++;
22             else{
23                 result << count << last;
24                 // result.append(count); 这里append无法实现,因为找不到itoa,很蛋疼,只能用stream来实现
25                 // result.append(last);
26                 last = prev[i];
27                 count = 1;
28             }
29         }
30         return result.str();
31     }
32 };

 

LeetCode OJ:Count and Say(数数)

原文:http://www.cnblogs.com/-wang-cheng/p/4896404.html

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