Share my simple and concise c++ solution


  • 1
    G
    class Solution {
    public:
        string countAndSay(int n) {
            string ret = "1";
            while(--n){
                int cnt = 1;
                string tmp;
                for(int i = 1; i < ret.size(); i++){
                    if(ret[i] == ret[i-1]) cnt++;
                    else{
                        tmp += to_string(cnt) + ret[i-1];
                        cnt = 1;
                    }
                }
                tmp += to_string(cnt) + ret.back();
                ret = tmp;
            }
            return ret;
        }
    };

Log in to reply
 

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