Sharing my simple C++ solution


  • 0
    T
    class Solution {
    private:
        string next(string s)
        {
            string result;
            int n = s.length();
            int start=0;
            for(int i=0; i<n; i++)
            {
                if(s[i]!=s[start])
                {
                    result = result + to_string(i-start) + s[start];
                    start=i;
                }
            }
            if(start<n)
                result = result + to_string(n-start) + s[start];
                
            return result;
        }
        
    public:
        string countAndSay(int n) {
            string s="1";
            if(n==1)
                return s;
            for(int i=1; i<n; i++)
                s = next(s);
                
            return s;
        }
    };

Log in to reply
 

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