38. Count and Say

2018-05-28  本文已影响0人  SilentDawn

Problem

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     111221

Given an integer n, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example

Input: 1
Output: "1"
Input: 4
Output: "1211"

Code

static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    string countAndSay(int n) {
        string str = "1";        
        if(n==1)
            return str;
        string tar = "";        
        for (int i = 0; i<n - 1; i++) {
            int count = 0;
            char tmp = str[0];
            for (int j = 0; j<str.size(); j++) {
                if (str[j] == tmp)
                    count++;
                else {
                    tar += to_string(count) + tmp;
                    count = 1;
                    tmp = str[j];
                }
            }
            tar += to_string(count) + tmp;
            str = tar;
            tar = "";
        }
        return str;
    }
};

Result

38. Count and Say.png
上一篇 下一篇

猜你喜欢

热点阅读