6. Z 字形变换
解法一:
/*n=numRows
Δ=2n-2 1 2n-1 4n-3
Δ= 2 2n-2 2n 4n-4 4n-2
Δ= 3 2n-3 2n+1 4n-5 .
Δ= . . . . .
Δ= . n+2 . 3n .
Δ= n-1 n+1 3n-3 3n-1 5n-5
Δ=2n-2 n 3n-2 5n-4
*/class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
length = len(s)
result = ""
for i in range(numRows): #一行行输出
step1 = 2*(numRows-1-i)
step2 = 2*i
pos = i #起始位置
if pos >= length:
break
result += s[pos]
while True:
pos += step1
if pos >= length: #直到pos越界
break
if step1: #step1不为0则输出
result += s[pos]
pos += step2
if pos >= length:
break
if step2:
result += s[pos]
return result最后更新于