题目描述
字符串“PAYPALISHIRING”以Z字形图案写在给定数量的行上,如下所示:(您可能希望以固定字体显示此图案以获得更好的易读性):
P A H N
A P L S I I G
Y I R
然后返回: "PAHNAPLSIIGYIR"
思路
先声明一个长度为numRows的列表,然后遍历原有字符串:
当当前索引:index==0时,step=1,如果当前索引index==numRows时,相当于控制遍历的上下方向。
代码实现
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows==1 or len(s)<=numRows:
return s
ans=['']*numRows
index,step=0,1
for x in s:
ans[index]+=x
if index==0:
step=1
elif index==numRows-1:
step=-1
index+=step
return "".join(ans)
同时安利大家一个代码执行模拟的网站:http://www.pythontutor.com/live.html#mode=edit
![1531909-729202a17cb073a4.png](https://i-blog.csdnimg.cn/blog_migrate/935195498ec4810b6e063c2344cb600d.webp?x-image-process=image/format,png)