@@ -282,6 +282,47 @@ public class Solution {
282282}
283283```
284284
285+ #### C
286+
287+ ``` c
288+ char * convert (char* s, int numRows) {
289+ if (numRows == 1) {
290+ return strdup(s);
291+ }
292+
293+ int len = strlen(s);
294+ char** g = (char**) malloc(numRows * sizeof(char*));
295+ int* idx = (int*) malloc(numRows * sizeof(int));
296+ for (int i = 0; i < numRows; ++i) {
297+ g[i] = (char*) malloc((len + 1) * sizeof(char));
298+ idx[i] = 0;
299+ }
300+
301+ int i = 0, k = -1;
302+ for (int p = 0; p < len; ++p) {
303+ g[i][idx[i]++] = s[p];
304+ if (i == 0 || i == numRows - 1) {
305+ k = -k;
306+ }
307+ i += k;
308+ }
309+
310+ char* ans = (char*) malloc((len + 1) * sizeof(char));
311+ int pos = 0;
312+ for (int r = 0; r < numRows; ++r) {
313+ for (int j = 0; j < idx[r]; ++j) {
314+ ans[pos++] = g[r][j];
315+ }
316+ free(g[r]);
317+ }
318+ ans[pos] = '\0';
319+
320+ free(g);
321+ free(idx);
322+ return ans;
323+ }
324+ ```
325+
285326<!-- tabs:end -->
286327
287328<!-- solution:end -->
@@ -491,41 +532,7 @@ class Solution {
491532 return $result;
492533 }
493534}
494- ```
495-
496- #### C
497-
498- ``` C
499- char *convert (char * s, int numRows) {
500- if (numRows == 1 || numRows >= strlen(s)) {
501- char * result = malloc(strlen(s) + 1);
502- strcpy(result, s);
503- return result;
504- }
505- char ** rows = malloc(numRows * sizeof(char * ));
506- for (int i = 0; i < numRows; i++) {
507- rows[ i] = malloc(strlen(s) + 1);
508- rows[ i] [ 0 ] = '\0';
509- }
510- int currentRow = 0;
511- int goingDown = 0;
512- for (int i = 0; s[ i] != '\0'; i++) {
513- strncat(rows[ currentRow] , &s[ i] , 1);
514- if (currentRow == 0 || currentRow == numRows - 1) {
515- goingDown = !goingDown;
516- }
517- currentRow += goingDown ? 1 : -1;
518- }
519- char * result = malloc(strlen(s) + 1);
520- result[ 0] = '\0';
521- for (int i = 0; i < numRows; i++) {
522- strcat(result, rows[ i] );
523- free(rows[ i] );
524- }
525- free(rows);
526- return result;
527- }
528- ```
535+ ``
529536
530537<!-- tabs:end -->
531538
0 commit comments