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)

1
2
3
P   A   H   N
A P L S I I G
Y I R

Write the code to convert a string to a zigzag pattern.

You should do it in-place.

Example 1:

1
2
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

1
2
3
4
5
6
7
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I

Approach

We can solve this problem by iterating over the string and keeping track of the current row and direction. We can use two pointers, one for the current row and one for the direction. We can then iterate over the string and add each character to the appropriate row based on the current row and direction.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
rows = [''] * numRows
row, direction = 0, 1
for char in s:
rows[row] += char
if (row == 0 and direction == -1) or row == numRows - 1:
direction = -direction
row += direction
return ''.join(rows)