题目
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下:
L C I R
E T O E S I I G
E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“LCIRETOESIIGEDHN”。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1
输入: s = “LEETCODEISHIRING”, numRows = 3
输出: “LCIRETOESIIGEDHN”
示例 2
输入: s = “LEETCODEISHIRING”, numRows = 4
输出: “LDREOEIIECIHNTSG”
解释:
L D R
E O E I I
E C I H N
T S G
代码
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1 or len(s) <= numRows:
return s
aim = [''] * numRows
direction = 1
currow = 0
for i in s:
aim[currow] += i
currow += direction
if currow == numRows-1 or currow == 0:
direction *= -1
end = ''
for i in aim:
end += i
return end
思路
顺序遍历字符串,模拟排列z字形。用变量currow
来记录当前排到的行数,用变量direction
来记录排列的方向,到达边界后反向。currow
根据direction
每次增加或减少1。用列表aim
中的元素来记录每一行输出的字母,例如,字母x
排到第currow
行,则将字母x
加到aim[currow ]
中。