首页 > 其他 > 详细

【leetcode】Count and Say

时间:2015-05-16 19:53:49      阅读:191      评论: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 n^th sequence.

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

 

 1 class Solution {
 2 public:
 3     string count(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             }else{
15                 ss<<count<<last;
16                 count=1;
17                 last=say[i];
18             }
19         }
20 
21         return ss.str();
22     }
23 
24 
25 
26     string countAndSay(int n) {
27         if(n==0) return string();
28 
29         string say="1";
30 
31         for(int i=1;i<n;i++)
32         {
33             say=count(say);
34         }
35 
36         return say;
37     }
38 };

 

【leetcode】Count and Say

原文:http://www.cnblogs.com/jawiezhu/p/4508251.html

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