Share my C solution


  • 0
    A
    char* convert(char* s, int numRows) {
      int i = 0;
      int len = strlen(s);
      if (len <= 2 || numRows == 1 || len < numRows)
        return s;
      char *argv[len];
      char *p = calloc(len +1, sizeof(char));
      for (i = 0; i < numRows; i++) {
        argv[i] = calloc(len+1, sizeof(char));
      }
      int skip = 1, row = 0;
      for (i = 0; i < len; i++) {
        strncat(argv[row], &s[i], 1);
        if (row == 0)
          skip = 1;
        else if (row == numRows - 1)
          skip = -1;
        row += skip;
      }
      for(i = 0; i < numRows; i++)
        strcat(p, argv[i]);
      for (i = 0; i < numRows; i++)
        free(argv[i]);
    
      return p;
    }
    

  • 0
    A

    @ashenkute I think there is a bug in leetcode that was causing a runtime error. It was running fine on my machine but giving me a runtime error on leetcode. It turned out using malloc was causing that. I changed it to calloc and no runtime error!


Log in to reply
 

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