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