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”-》“11”-》“21”-》“1211”-》...得到第N个字符串是多少
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
    string countAndSay(int n) {
        string result = "1";
        for(int i = 1; i < n; ++i){
            result = nextStr(result);
        }
        return result;
    }
     
    string nextStr(string s){
        char last = 0;
        int count = 1;
        string result = "";
        for(int i = 0; i < s.size(); ++i){
            if(last != s[i]){
                if(i != 0)result += to_string(count) + last;
                count = 1;
                last = s[i];
            }
            else{
                count++;
            }
        }
        result += to_string(count) + last;
        return result;
    }
};




posted @ 2017-02-08 09:36  copperface  阅读(181)  评论(0编辑  收藏  举报