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”
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = “PAYPALISHIRING”, numRows = 3
Output: “PAHNAPLSIIGYIR”
Example 2:
Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:
P I N
A L S I G
Y A H R
P I
纵向思维考虑,index从0开始,我们要一直自增直到numRows-1,此后又一直自减到0,重复执行。 给个例子容易懂一些:s = “abcdefghijklmn”, numRows = 4
a g m
b f h l n
c e i k
d j
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1 or numRows >= len(s):
return s
res = [''] * numRows
idx, step = 0, 1
for x in s:
res[idx] += x
if idx == 0: ## 第一行,一直向下走
step = 1
elif idx == numRows - 1: ## 最后一行了,向上走
step = -1
idx += step
return ''.join(res)