题目:
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
给定一个字串,将其变为zigzag模式,按第一行往下,每行由左至右的顺序得出一新字串回传
题目还会给定一数numRows,表示要转成有numRows行的zigzag模式
zigzag模式就是上面题目之字型的模样
看似没有什么规律
但我们把字串每个字元应该在第几行列出后,就能看到一些蛛丝马迹
以"PAYPALISHIRING"为例
字串字元:PAYPALISHIRING
应在行数:12321232123212
可以看出行数是1到numRows,numRows到1不断重複的变化
抓到规律我们就能开始实作了
class Solution: def convert(self, s: str, numRows: int) -> str: if numRows==1: #假如numRows为1,直接回传原字串即可 return s record=[""]*numRows direct="+" n=1 for i in s: if direct=="+": record[n-1]=record[n-1]+i n=n+1 if n==numRows: direct="-" else: record[n-1]=record[n-1]+i n=n-1 if n==1: direct="+" ans="" for i in record: ans=ans+i return ans
我们先宣告一个有numRows个空字串的阵列
準备用来存每一行的字元
我们会以1到numRows,numRows到1的循环顺序一一将字串里的字元放入各行
为了知道何时往上何时往下,我设立了一个指标direct储存现在要走的方向
当一碰到第1或numRows行,就改变direct,改变方向
而我们纪录完毕后,只要将各行字串相加回传即可
最后执行时间54ms(faster than 96.53%)
那我们下题见