解法一:使用二维数组
def convert(s, numRows):
if numRows == 1 or numRows >= len(s):
return s
rows = [''] * numRows
index, step = 0, 1
for char in s:
rows[index] += char
if index == 0:
step = 1
elif index == numRows - 1:
step = -1
index += step
return ''.join(rows)
解法二:使用列表存储每行的字符
def convert(s, numRows):
if numRows == 1 or numRows >= len(s):
return s
rows = [[] for _ in range(numRows)]
index, step = 0, 1
for char in s:
rows[index].append(char)
if index == 0:
step = 1
elif index == numRows - 1:
step = -1
index += step
result = ''
for row in rows:
result += ''.join(row)
return result
解法三:直接计算字符在每行的索引位置
def convert(s, numRows):
if numRows == 1 or numRows >= len(s):
return s
n = len(s)
cycle_len = 2 * numRows - 2
result = ''
for i in range(numRows):
for j in range(i, n, cycle_len):
result += s[j]
if i != 0 and i != numRows - 1 and j + cycle_len - 2 * i < n:
result += s[j + cycle_len - 2 * i]
return result
标签:index,rows,字形,python,len,numRows,step,result,解法
From: https://blog.51cto.com/lzning/8801680