# 6. Zigzag Conversion

## 08 Jan 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
```

Example 3:

```Input: s = "A", numRows = 1
Output: "A"
```

Constraints:

• `1 <= s.length <= 1000`
• `s` consists of English letters (lower-case and upper-case), `','` and `'.'`.
• `1 <= numRows <= 1000`

##### 解决思路

###### 思路1

``````class Solution:
def convert(self, s, numRows):
if numRows <= 1:
return s

n = 2*numRows-2
temp_str = ['']*numRows
temp_dict = {
}

for t in range(n):
if t>=0 and t<numRows:
temp_dict[t] = t
else:
temp_dict[t] = n-t

for i in range(len(s)):
temp_str[temp_dict[i%n]] += s[i]

return ''.join(temp_str)
``````

###### 思路二 1

``````class Solution:
def convert(self, s, numRows):
if not numRows > 1:
return s
if numRows == 2:   #做了一个特例处理
return s[::2]+s[1::2]

temp_str = ['']*numRows
i = 0
n = len(s)
while i < n:
for j in range(numRows):
if i < n:
temp_str[j] += s[i]
i += 1

for k in range(numRows - 2, 0, -1):
if i < n:
temp_str[k] += s[i]
i += 1
return ''.join(temp_str)
``````

1. darede在leetcode题解中回答 ：https://leetcode-cn.com/problems/zigzag-conversion/solution/6-zzi-bian-huan-python3-an-xing-qu-zhi-by-darede/
``````class Solution:
def convert(self, s: str, numRows: int) -> str:
print(s)
print(numRows)
if len(s) <= 1 or numRows == 1:
return s

n = numRows * 2 - 2

tmp_dict = {}
tmp_str = [''] * numRows

for i in range(n):
if i >=0 and i < numRows:
tmp_dict[i] = i
else:
tmp_dict[i] = n - i
print(tmp_dict)
m = len(s)
for j in range(m):
print(j)
print(j % n)
tmp_row_index = tmp_dict[j % n]
print(tmp_row_index)
tmp_str[tmp_row_index] += s[j]
print("-------------------")

return ''.join(tmp_str)``````