Description
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);
Solution
直接模拟即可。注意特判numRows == 1的情况
Code
class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
if numRows == 1:
return s
arr = [''] * numRows
i = 0
di = 1
for c in s:
arr[i] += c
if di > 0:
if i == numRows - 1:
di = -1
else:
if i == 0:
di = 1
i += di
res = ""
for row in arr:
res += row
return res
sol = Solution()
print(sol.convert('ABC', 1))