Share my easy-to-understand 0ms recursive solution (C++)


  • 0
    P
    class Solution {
    public:
        string countAndSay(int n) {
            if (n==1) return "1";
            else{
                string s = countAndSay(n-1);
                char c=s[0];
                int count=1;
                string ans;
                if (s.size() == 1) 
                {
                    ans = count + '0';
                    ans += c;
                }
                else {
                    for(int i=1; i<s.size();++i) 
                    {
                        if (c == s[i]) ++count;
                        else {
                            ans+=(count+'0');
                            ans+=c;
                            count = 1;
                            c = s[i];
                        }
                    }
                    ans+=(count+'0');
                    ans+=c;
                }
                return ans;
            }
        }
    };

Log in to reply
 

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