-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblems6.c
More file actions
71 lines (55 loc) · 1.17 KB
/
problems6.c
File metadata and controls
71 lines (55 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//problems6.c
//6. ZigZag Conversion
//Solution:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
char* convert(char* s, int numRows)
{
int length = strlen(s);
if ((length == 0) || (numRows == 0) || (numRows == 1))
return s;
int unit = 2 * numRows - 2;
int collum = length/unit;
if (length % unit != 0)
{
collum++;
}
char *t = (char *)malloc(length + 1);
assert(t);
t[length] = '\0';
//for the first row
int index = 0;
for (int j = 0; j < collum; j++)
{
*(t + index++) = *(s + j * unit);
//index++;
}
for (int i = 1; i < numRows; i++)
{
for (int j = 0; j < collum; j++)
{
int left = j * unit + i;
int right = (j + 1) * unit - i;
if (left >= length)
{
break;
}
*(t + index++) = *(s + left);
if ((right < length) && (right != left))
*(t + index++) = *(s + right);
}
}
strncpy(s, t, length);
free(t);
return s;
}
int main(int argc, char *argv[])
{
char a[] = "PAYPALISHIRING";
char *b = convert(a, 1);
printf("\r\n a after convert is %s", b);
printf("\r\n");
return 0;
}