my 0ms C++ solution


  • 0
    J

    Note that:

    • Two strings s0, s1 are used for the old and new iteration. Their contents are swapped after each iteration.
    • A sentinel '2' are pushed back to s0 to deal with boundary.
    class Solution {
    public:
        string countAndSay(int n) {
            string s0("1"), s1;
            for(int i = 0; i != n-1; ++i){
                s0.push_back('2');  //sentinel
                for(int j = 1, cnt = 1; j != s0.size(); ++j){
                    if(s0[j] == s0[j-1]) cnt++;
                    else{
                        s1.push_back('0' + cnt);
                        s1.push_back(s0[j-1]);
                        cnt = 1;
                    }
                }
                s0.clear();  swap(s0, s1);
            }
            return s0;
        }
    };
    

Log in to reply
 

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