Description
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
L C I R
E T O E S I I G
E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:
"LCIRETOESIIGEDHN"
。
示例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
Solution
def convert(s, numRows):
if numRows <= 1:
return s
n = len(s)
convertStr = ""
# 第一行和最后一行间隔 / 最长间隔
maxGap = 2 * (numRows - 1)
# 构造z的每一行,共numRows行
for i in range(numRows):
# 索引
index = i
if i == 0 or i == numRows-1:
while index < n:
convertStr += s[index]
index += maxGap
else:
g1 = 2 * (numRows - i - 1)
g2 = maxGap - g1
# j用来计数
j = 1
while index < n:
convertStr = convertStr + s[index]
if j % 2 != 0:
index = index + g1
else:
index = index + g2
j += 1
return convertStr
s = 'LEETCODEISHIRING'
print(convert(s, 4))
print('LDREOEIIECIHNTSG')
提交记录:

网友评论