My 2ms non-recursive solution


  • 0
    R
    string countAndSay(int n) 
    {
        string s;
        if (n < 1)
            return s;
            
        int i = 1;
        s = '1';
        while (i < n) 
        {
            string temp;
            int cnt = 1;
            for (int j=0; j<s.length(); ++j)
            {
                if (j+1 < s.length() && s[j] == s[j+1])
                {
                    ++cnt;
                }
                else
                {
                    temp += char(cnt + '0');
                    temp += s[j];
                    cnt = 1;
                }
            }
            
            s = temp;
            ++i;
        }
    
        return s;
    }

Log in to reply
 

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