8ms C solution, easy to understand


  • 15
    C
    char* convert(char* s, int numRows) {
    int n=strlen(s);
    char* a;
    int k=0;
    if(numRows==1 || n<=numRows)return s;
    for(int i=0;i<numRows;i++)
    {
        for(int j=i;j<n;j+=2*(numRows-1))
        {
            a[k++]=s[j];
            if(i!=0 && i!=numRows-1)
            {
              int t=j+2*(numRows-1)-2*i;
              if(t<n)
              a[k++]=s[t];
            }
        }
    }
    a[k]='\0';
       return a;
    

    }


  • 0
    L

    It is really easy to implement and effective!


  • 0
    _

    Yes, it's really simple!


  • 0
    X

    great ,simple and easy to understand!


  • 1
    J

    the pointer a is a floating pointer, are you sure it works?


  • 0
    C

    the pointer a is a char pointer,not float.


  • 0
    J

    sorry, I mean a is wild pointer, which you did not initialize.


  • 0
    S

    Yeah, I also think some memory should be allocated first by initializing pointer a.
    This code gives segmentation fault in my system.


  • 0
    C

    All right,Your advice is very good, this is my fault. But this code can be running on this OJ.I mean this algorithm is correct.


  • 0
    C

    Yes! you are right. I should initializing pointer a. thanks for your suggestion . But this code can be running on this OJ.I mean this algorithm is correct.


  • 0
    C

    It's a great and simple solution! I created 2-dimensional array in java. Though clumsy but it worked. But it's strange that I rewrited your code in java, it ended in "memory limit exceeded". So sad I cannot use this method in java. However, I think math skill is very important!


  • 0
    C

    I don't know how to use java,but I think it related to language, not method. for example,use pointer is different in C and Java.


  • 0
    Y
    This post is deleted!

Log in to reply
 

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