# 6. Zigzag Conversion Z 字形变换

@TOC

## # 题目描述

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

## # 解题方法

### # 公式

1. 第一行和最后一行下标间隔都是 `interval = n*2-2 = 8`;
2. 中间行的间隔是周期性的,第 `i` 行的间隔是: `interval–2*i` , `2*i`, `interval–2*i` , `2*i`, `interval–2*i`, `2*i`, …

Python 代码如下：

``````class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1: return s
ans = ""
interval = 2 * (numRows - 1)
for i in range(0, len(s), interval):
ans += s[i]
for row in range(1, numRows - 1):
inter = 2 * row
i = row
while i < len(s):
ans += s[i]
inter = interval - inter
i += inter
print(ans)
for i in range(numRows - 1, len(s), interval):
ans += s[i]
return ans
``````

## # 日期

2018 年 6 月 27 日 ———— 阳光明媚，心情大好，抓紧科研啊