[leetcode题解]6. ZigZag Conversion

The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

```P   A   H   N
A P L S I I G
Y   I   R
```

And then read line by line: “PAHNAPLSIIGYIR”

Write the code that will take a string and make this conversion given a number of rows:

`string convert(string s, int numRows);`

Example 1:

```Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
```

Example 2:

```Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P     I    N
A   L S  I G
Y A   H R
P     I```

```P   A   H   N
A P L S I I G
Y   I   R
```

`string convert(string s, int numRows);`

```输入: s = "PAYPALISHIRING", numRows = 3 输出: "PAHNAPLSIIGYIR"
```

```输入: s = "PAYPALISHIRING", numRows = 4 输出: "PINALSIGYAHRPI" 解释: P     I    N
A   L S  I G
Y A   H R
P     I```

`纯模拟题，简单找一下规律就可以了，然后直接输出就行，代码如下：`
```char* convert(char* s, int numRows) {
int len = strlen(s);
char *sres = calloc(1, len + 1);
int i = 0;
int j = 0;
int pos = 0;
int gap = (numRows - 1) * 2;
int step = 0;

if (numRows <= 1)
return s;

for (i = 0; i < numRows; i++) {
step = 2 * (numRows - i % (numRows - 1) - 1);
for (j = i; j < len;) {
sres[pos++] = s[j];
j += step;
step = gap - step;
if (step == 0)
step = gap - step;
}
}

return sres;
}