16-line Clean Recursion C++ Solution


  • 4
    L
    class Solution {
    public:
        string countAndSay(int n) {
            if(n==1) return "1"; // base case
            string res,tmp = countAndSay(n-1); // recursion
            char c= tmp[0];
            int count=1;
            for(int i=1;i<tmp.size();i++)
                if(tmp[i]==c)
                    count++;
                else {
                    res+=to_string(count);
                    res.push_back(c);
                    c=tmp[i];
                    count=1;
                }
            res+=to_string(count);
            res.push_back(c);
            return res;
        }
    };

Log in to reply
 

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