38. 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.     1
 2.     11
 3.     21
 4.     1211
 5.     111221 
 6.     312211
 7.     13112221
 8.     1113213211
 9.     31131211131221
 10.   13211311123113112211

n为几就输出第几行

 

C++(6ms):

 1 class Solution {
 2 public:
 3     string build(string res , int len){
 4        string t ;
 5        int count = 1 ;
 6        for (int j = 0; j < len;j++ ){
 7             if(res[j] == res[j+1]){
 8                 count++ ;
 9             }else{
10                 t+=to_string(count);
11                 t+=res[j] ;
12                 count = 1 ;
13             }
14         }
15         return t ;
16     }
17 
18     string countAndSay(int n) {
19         string res = "1" ;
20         int len ;
21         for (int i = 1; i < n;i++ ){
22             len = res.size() ;
23             res = build(res,len) ;
24         }
25         return res ;
26     }
27 };

 

posted @ 2017-03-29 19:55  __Meng  阅读(147)  评论(0)    收藏  举报