C O(n) Solution


  • 1
    H
    char* convert(char* s, int numRows) {
    int len=strlen(s);
    if(len<=numRows || numRows==1){
        return s;
    }
    int step = 2*numRows-2;
    int i=0,j=0,myStep=0,it=0;
    char *ns=(char*)malloc(sizeof(char)*(len+1));
    for(i=0;i<len+1;i++){
        ns[i]=0;
    }
    for(i=0;i<numRows;i++){
        j=i;
        myStep=step-2*i;
        while(j<len){
            ns[it++]=s[j];
            if(!(i==0|| i==numRows-1)){
                if(j+myStep<len){
                    ns[it++]=s[j+myStep];
                }
            }
            j+=step;
        }
    }
      return ns;
     }

  • 0
    H

    0 10

    1 9 11

    2 8 12

    3 7 13

    4 6 14

    5 15

    step = 2*6-2 = 10

    if current row isn't equal 1 or numRows, then
    myStep = step - 2*(current row -1).
    such as row2's myStep is 10-2*(2-1)=8 ,row5's myStep is 10-2*(5-1)=2.


Log in to reply
 

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