c++ 4ms solution (straightforward idea)


  • 0
    class Solution {
    public:
        string countAndSay(int n) {
            string res;
            while(n--)
            {
                if(res.empty())
                    res = "1";
                else
                {
                    string tmp;
                    for(int i=0; i<res.size(); i++)
                    {
                        int cnt = 1;
                        while(i+1<res.size() && res[i]==res[i+1])
                        {
                            cnt++;
                            i++;
                        }
                        tmp += to_string(cnt) + res[i];
                    }
                    res = tmp;
                }
            }
            return res;
        }
    };

Log in to reply
 

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