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"
class Solution(object):
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1 or len(s) < numRows:
return s
row = 0
step = 1
zigzag = ['' for i in range(numRows)]
for item in s:
zigzag[row] += item
if row == 0:
step = 1
elif row == numRows - 1:
step = -1
row += step
return ''.join(zigzag)