C++ Solution


  • 0
    M
    class Solution {
    public:
        string countAndSay(int n) {
            string s = "1";
            for (int i = 2; i <= n; ++i) {
                string ns;
                int cnt = 0;
                char c = s[0];
                for (int j = 0; j < s.size(); ++j) {
                    if (s[j] == c) {
                        ++cnt;
                    } else {
                        ns += to_string(cnt) + string(1, c);
                        c = s[j];
                        cnt = 1;
                    }
                }
                ns += to_string(cnt) + string(1, c);
                s = ns;
            }
            return s;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.