# 6. ZigZag Conversion

## 刷题内容

• https://leetcode.com/problems/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


## 解题方案

a   g   m
b f h l n
c e i k
d   j


class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1 or numRows >= len(s):
return s
res = [''] * numRows
idx, step = 0, 1

for x in s:
res[idx] += x
if idx == 0:  ## 第一行，一直向下走
step = 1
elif idx == numRows - 1: ## 最后一行了，向上走
step = -1
idx += step
return ''.join(res)


(0, 1, ['a', '', '', ''])
(1, 1, ['a', 'b', '', ''])
(2, 1, ['a', 'b', 'c', ''])
(3, 1, ['a', 'b', 'c', 'd'])
(2, -1, ['a', 'b', 'ce', 'd'])
(1, -1, ['a', 'bf', 'ce', 'd'])
(0, -1, ['ag', 'bf', 'ce', 'd'])
(1, 1, ['ag', 'bfh', 'ce', 'd'])
(2, 1, ['ag', 'bfh', 'cei', 'd'])
(3, 1, ['ag', 'bfh', 'cei', 'dj'])
(2, -1, ['ag', 'bfh', 'ceik', 'dj'])
(1, -1, ['ag', 'bfhl', 'ceik', 'dj'])
(0, -1, ['agm', 'bfhl', 'ceik', 'dj'])
(1, 1, ['agm', 'bfhln', 'ceik', 'dj'])


apachecn/AiLearning