share my concise code


  • 0
    P
    class Solution {
    public:
        string countAndSay(int n) {
            std::string start("1");
            for (int i = 1; i < n; ++ i) {
                start = getNext(start);
            }
            return start;
        }
    private:
        std::string getNext(const std::string& s) {
            std::string res;
            for (int i = 0; i < s.size(); ++ i) {
                int j(i + 1);
                while (j < s.size() && s[j] == s[i]) ++ j;
                res += std::to_string(j - i) + s[i];
                i = j - 1;
            }
            return res;
        }
    };
    

Log in to reply
 

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