C++ concise solution.


  • 0
    C
    string countAndSay(int n) {
        string res = "1";
        for (int i = 1; i < n; i++) {
            string tmp = "";
            int count = 1;
            unsigned idx = 0;
            while (idx < res.size()) {
                while (idx+1 < res.size() && res[idx] == res[idx+1]) {
                    idx++;
                    count++;
                }
                tmp += to_string(count)+res[idx++];
                count = 1;
            }
            res = tmp;
        }
        return res;
    }

  • 0
    C

    char* countAndSay(int n) {
    int i,j;
    int count;
    char cur = (char )malloc(102420sizeof(char));
    char next = (char )malloc(102420sizeof(char));

    cur[0]='1';cur[1]='\0';
    while(--n){
        i=0;j=0;
        while(cur[i]!='\0'){
            count=1;
            while(cur[i]==cur[i+1]){
                i++;count++;
            }
            next[j++]=count+'0';
            next[j++]=cur[i];
            i++;
        }
        next[j]='\0';
        strcpy(cur,next);
    }
    return cur;
    

    }


Log in to reply
 

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