0ms. Sharing a Real C++ solution. Easy to understand.


  • 0
    S
    class Solution {
    public:
        string convertCnS(string &str)
        {
            stringstream sstr;
            char digit = 0;
            int repeated = 0;
        
            for (int i=0; i<str.length(); ++i)
            {
                if (str[i] == digit)
                {
                    ++repeated;
                }
                else
                {
                    if (digit != 0)
                        sstr << repeated << digit;
        
                    digit = str[i];
                    repeated = 1;
                }
            }
        
            if (repeated !=0)
                sstr << repeated << digit;
        
            return sstr.str();
        }
    
        string countAndSay(int n)
        {
            if (n == 1)
            {
                return "1";
            }
        
            string generated = countAndSay(n-1);
            string converted = convertCnS(generated);
            return converted;
        }
    };

Log in to reply
 

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