6.锯齿形变换
题目描述
给定一个字符串s和整数n, 求s做n行的锯齿形变换后, 顺序拼写而成的新字符串.
比如: s=“PAYPALISHIRING”, n=3, 锯齿形变换如下:
P A H N
A P L S I I G
Y I R
再顺序从左到右, 从上到下的拼接成的字符串为: “PAHNAPLSIIGYIR”
解法分析
这道题最难的地方在于对题意的理解. 什么叫做锯齿形变换呢? 说白了, 就是按照下面这种顺序, 将原字符串的字符一个个的放到指定位置.
| /| /|
| / | / |
| / | / |
|/ |/ |
class Solution:
def convert(self, s: str, numRows: int) -> str:
n=len(s)
if numRows==1:
return s
table=[[]for i in range(numRows)]
i=0
while i<n:
idx=0
while idx<numRows and i<n:
table[idx].append(s[i])
idx+=1
i+=1
idx=numRows-2
while idx>=1 and i<n:
table[idx].append(s[i])
idx-=1
i+=1
res=''
for i in range(numRows):
res+="".join(table[i])
return res