forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: begeekmyfriend <[email protected]>
- Loading branch information
1 parent
f416763
commit 3b530e7
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test zigzag_conversion.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
#include <string.h> | ||
|
||
static char* convert(char* s, int numRows) { | ||
if (numRows <= 1) return s; | ||
|
||
int len = strlen(s); | ||
char *new_str = malloc(len + 1); | ||
char *p = new_str; | ||
int row = 0; | ||
for (row = 0; row < numRows; row++) { | ||
int interval1 = numRows + (numRows - 2) - row * 2; | ||
int interval2 = 2 * row; | ||
int flag = 0; | ||
int i = row; | ||
while (i < len) { | ||
*p++ = s[i]; | ||
int delta = 0; | ||
do { | ||
delta = flag == 0 ? interval1 : interval2; | ||
flag = !flag; | ||
} while (delta == 0); | ||
i += delta; | ||
} | ||
} | ||
|
||
new_str[len] = '\0'; | ||
return new_str; | ||
} | ||
|
||
int main(int argc, char **argv) | ||
{ | ||
if (argc < 3) { | ||
fprintf(stderr, "./test string num\n"); | ||
exit(-1); | ||
} | ||
|
||
printf("%s\n", convert(argv[1], atoi(argv[2]))); | ||
return 0; | ||
} |