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

【LeetCode】38 - Count and Say

时间:2015-08-10 01:40:04      阅读:103      评论: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.

Solution:下一个字符串= 当前字符串:∑(字符个数+字符),例如1211,下一个字符串=count(1)+‘1‘+count(2)+‘2‘+count(1)+‘1‘=111221

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         string ret="1";
 5         if(n==1)return ret;
 6         while(--n){
 7             string next;
 8             char last=ret[0];
 9             int i=1,count=1;
10             while(i<ret.size())
11             {
12                 while(ret[i]==last&&i<ret.size()){
13                     i++;
14                     count++;
15                 }
16                 if(i<ret.size()&&ret[i]!=last){
17                     next+=to_string(count);
18                     next+=last;
19                     
20                     count=1;
21                     last=ret[i];
22                     i++;
23                 }
24             }
25             next+=to_string(count);
26             next+=last;
27             ret=next;
28         }
29         return ret;
30     }
31 };

 

【LeetCode】38 - Count and Say

标签:

原文地址:http://www.cnblogs.com/irun/p/4716797.html

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