## 题目描述：

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 text, int nRows);`

`convert("PAYPALISHIRING", 3)` should return `"PAHNAPLSIIGYIR"`.

## 题目大意：

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

`string convert(string text, int nRows);`

convert("PAYPALISHIRING", 3)应当返回“PAHNAPLSIIGYIR”。

## Python代码：

``````class Solution:
# @param {string} s
# @param {integer} numRows
# @return {string}
def convert(self, s, numRows):
if numRows == 1 or numRows >= len(s):
return s
zigzag = [[] for x in range(numRows)]
row, step = 0, 1
for c in s:
zigzag[row] += c,
if row == 0:
step = 1
elif row == numRows - 1:
step = -1
row += step
``````

``````def convertRowNum(self, idx, numRows):
return numRows -1 - abs(numRows - 1 - i % (2 * numRows - 2))
``````

zigzag字符串中字母所在的行号序列为：

`1, 2, ... , numRows - 1, numRows, numRows - 1, ... 2, 1`

## Python代码：

``````class Solution:
# @param {string} s
# @param {integer} numRows
# @return {string}
def convert(self, s, numRows):
if numRows == 1 or numRows >= len(s):
return s
final = [[] for row in xrange(numRows)]
for i in range(len(s)):
final[numRows -1 - abs(numRows - 1 - i % (2 * numRows - 2))].append(s[i])
return "".join(["".join(final[i]) for i in xrange(numRows)])
``````

Pingbacks已关闭。