https://leetcode.com/problems/zigzag-conversion/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);
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
The idea is just clear: use numRows character strings to record characters in each row. Traverse the original string s, we need to know which direction are we going, up or down, use True or False to represent this status. Finally, merge all rows.
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
rows = ['' for _ in range(numRows)]
curr = [0, True]
for char in s:
rows[curr[0]] += char
if curr[1]:
curr[0] += 1
else:
curr[0] -= 1
if curr[0] == 0:
curr[1] = True
if curr[0] == numRows - 1:
curr[1] = False
return ''.join(rows)