C++ Implementation with a little explanation


  • 1
    A
    class Solution {
    public:
        string countAndSay(int n) {
            string curr_str = "1"; // Starts with only a '1'
            for (int i=0;i<n-1;i++) { // The result of the (n-1)th counting is the nth sequence, so loop until i==n-2
                string buffer; // buffer is what we get after counting the different digits in curr_str
                for (int j=0;j<curr_str.size();j++) {
                    int cnt = 0;
                    char ch = curr_str[j];
                    while (j<curr_str.size() && curr_str[j] == ch) {
                        j++;
                        cnt++;
                    }
                    buffer += (to_string(cnt)+ch);
                    j--; // We are one step further from the last sequence of ch, so we need j-- before j++ executed in the j-for-loop, otherwise one digit will be skipped
                }
                curr_str = buffer; // Update curr_str
            }
            return curr_str;
        }
    };
    

Log in to reply
 

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