Share my code in C (8ms)


  • 0
    H
    char* convert(char* s, int numRows) {
    if(numRows == 1) return s;
    int len = strlen(s);
    int section_len = numRows * 2 - 2;
    int sections = len / section_len + 1;
    char *ret = malloc(len  + 1);
    int i, count = 0, flag = 0;;
    for(i = 0; i * section_len < len; ++i){ret[count] = s[i * section_len]; ++count;}
    if(numRows > 2){
        for(int rows = 1; rows < numRows - 1; ++rows){
            for(i = 0;; ++i){
                flag = 1;
                if(i * section_len + rows < len){
                    ret[count] = s[i * section_len + rows];
                    ++count;
                    flag = 0;
                }
                if(i * section_len + section_len - rows < len){
                    ret[count] = s[i * section_len + section_len - rows];
                    ++count;
                    flag = 0;
                }
                if(flag){
                    break;
                }
            }
        }
    }
    for(i = 0; i * section_len + numRows - 1 < len; ++i){ret[count] = s[i * section_len + numRows - 1]; ++count;}
    ret[count] = '\0';
    return ret;}

Log in to reply
 

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