My C code for ZigZag conservation problem. Running time error.


  • 0
    L
    char* convert(char* s, int numRows) {
    int strlength = 0, numColums, numSegment, rowi, colj, i, j;
    while ( s[strlength] != '\0'){
        strlength++;
    }
    
        char *newstring = (char *)malloc(sizeof(char) * strlength);
        char *convert2 = (char *)malloc(sizeof(char) * strlength);
    
    if (numRows == 1 || numRows >= strlength) {
        free(newstring);free (convert2);
         return s;
     }
    
    
    if (numRows == 2) {
        numColums = (strlength+1) / 2;
        for (i = 0; i < strlength; i++)
        {
            if (i < numColums){newstring[i] = s[2*i];}
            else {newstring[i] = s[(i - numColums+1)*2-1];}
        }
        return newstring;         
    }
    
    numSegment = numRows - 2 + numRows;
    if ( strlength % numSegment <= numRows && strlength % numSegment > 0 ){
        numColums = strlength / numSegment*(numRows - 1) + 1;
    }
    else numColums = strlength / numSegment *(numRows -1) + strlength % numSegment - numRows + 1;
    for (i = 0; i < numColums*numRows; i++) newstring[i] = '\0';
    for (i = 0; i < strlength; i++){
        colj = i / numSegment;
        rowi = i % numSegment;
        if(rowi < numRows){
            colj = colj * (numRows - 1);
            rowi = rowi;
        }
        else {
            colj = colj * (numRows - 1) + rowi - numRows + 1;
            rowi = rowi - numRows + 1;
        }
        newstring[colj+numColums*rowi] = s[i];
    }
    j = 0;
    for(i = 0; i < strlength; i++){
        while( newstring[j] =='\0' ){ j++; }
       convert2[i] = newstring[j];
        j++;
    }
    return convert2;
    

    }

    running time error for the input:
    Apalindromeisaword,phrase,number,orothersequenceofunitsthatcanbereadthesamewayineitherdirection,withgeneralallowancesforadjustmentstopunctuationandworddividers.10

    However I could get the result in my laptop with a result

    A,tsaclmapepmhctrmttgloecniaA,tsaclmapepmhctrmttgloecniaA,tsaclmapepmhctrmttgloecniaA,tsaclmapepmhctrmttgloecniaA,tsaclmapepmhctrmttgloecniaA,tsaclmapepmhctrmtta

    real 0m12.403s
    user 0m0.001s
    sys 0m0.002s

    I know i might make a stupid mistake. But could anyone help me?


  • 0
    C

    Your code looks very complicated,are you sure you find the rules?


Log in to reply
 

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