链接:
题目:
将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下:
L C I R E T O E S I I G E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“LCIRETOESIIGEDHN”。
我的解法:
class Solution(object):
def convert(self, s, numRows):
if numRows == 1:
return s
res = ["" for x in range(numRows)]
# num个数一循环
num = numRows*2-2
for i in range(len(s)):
# idx是在一个循环中是第几个数
idx = (i + 1) % num
idx = idx if idx != 0 else num
# row是在第几行append
row = numRows - abs(idx-numRows) - 1
res[row] += s[i]
result = "".join(res)
return result
别人的解法: 判断方向 维护index
class Solution(object):
def convert(self, s, numRows):
if numRows == 1 or numRows >= len(s):
return s
res = [""] * numRows
index = 0
down = True
for letter in s:
res[index] += letter
if index == numRows - 1: down = False
if index == 0: down = True
index = index + 1 if down else index - 1
return "".join(res)