码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode(38)

时间:2015-03-30 20:54:46      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

Count and Say

 

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和2 的数量。

 1 class Solution {
 2 public:
 3     string unguarded_convert(const string &say)
 4 {
 5     stringstream ss;
 6     int count = 0;
 7     char last = say[0];
 8     
 9     for (size_t i = 0; i <= say.size(); ++i)
10     {
11         if (say[i] == last)
12         {
13             ++count;
14         }
15         else
16         {
17             ss << count << last;
18             count = 1;
19             last = say[i];
20         }
21     }
22     
23     return ss.str();
24 }
25  
26 string countAndSay(int n) 
27 {
28     if (n <= 0) return string();
29     
30     string say = "1";
31     
32     for (int i = 1; i < n; ++i)
33     {
34         say = unguarded_convert(say);
35     }
36     
37     return say;
38 }
39 };

 

leetcode(38)

标签:

原文地址:http://www.cnblogs.com/zongmeng/p/4378940.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!