[LeetCode .38] Count and Say

Count and Say.

Problem

n = 1, “1”로 시작하여 주어진 N으로 문자열을 출력
규칙은 N-1번쨰의 문자열을 뒤에서 부터 같은 숫자가 몇개 있는지를
문자열로 소리나는대로 적으면된다.

Ex)
1. 1
2. 11
3. 21
4. 1211
5. 1111221

Solution

Recurrent

Code

class Solution {
public:
    string dp[31] = {"",};
    string countAndSay(int n) {

        if (n == 1) return "1";

        string say = countAndSay(n - 1);
        vector<string> tmp;
        int idx = say.size() - 1;
        while (idx >= 0) {
            tmp.push_back(to_string(say[idx] - '0'));
            int cnt = 1;
            while (idx > 0 && say[idx] == say[idx - 1]) {
                cnt++, idx--;
            }
            tmp.push_back(to_string(cnt));
            idx--;
        }
        reverse(tmp.begin(), tmp.end());
        string result = "";

        for (string str : tmp) result += str;

        return result;
    }
};