Share my c code, easy understand


  • 0
    K

    class Solution {

    public:

    string countAndSay(int n) {
        if (n < 1)
            return string("");
    
        string result = "1";
        
        for (int i = 1; i < n; i++)
            result = say(result);
    
        return result;
    }
    

    private:

    string say(string seq) {
        string newseq;
        int count = 0;
        char dup = seq[0];
        
        for (int i = 0; i < seq.size(); i++) {
            if (seq[i] == dup) {
                count++;
            }
            else {
                newseq += to_string(count) + dup;
                dup = seq[i];
                count = 1;
            }
        }
        
        if (count != 0)
            newseq += to_string(count) + dup;
        
        return newseq;
    }
    

    };


Log in to reply
 

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