# 6. ZigZag Conversion

## Description

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
``````

Tags: String

## 题意

``````0                           2n-2                        4n-4
1                    2n-3   2n-1                 4n-5   4n-5
2              2n-4         2n               4n-6       .
.           .               .             .             .
.       n+1                 .          3n-1             .
n-2   n                     3n-4   3n-2                 5n-6
n-1                         3n-3                        5n-5
``````

## 题解

### 思路1

``````func convert(s string, numRows int) string {
if numRows == 1 || numRows <= 0 || numRows > len(s) {
return s
}
strArr := make([][]byte, numRows)
j := 0
increasing := true

for i := 0; i < len(s); i++ {
strArr[j] = append(strArr[j], s[i])

if increasing {
j++
if j == numRows - 1 {
increasing = false
}
} else {
j--
if j == 0 {
increasing = true
}
}
}
res := make([]byte, 0)

for _, str := range strArr {
res = append(res, str...)
}
return string(res)
}
``````

```