Write the characters of a string s in a zigzag pattern over num_rows rows, then read the pattern line by line and return the resulting string.
For example, "PAYPALISHIRING" written on 3 rows looks like this:
P A H N
A P L S I I G
Y I R
Reading it line by line gives "PAHNAPLSIIGYIR".
Function Signature
def convert(s: str, num_rows: int) -> str:
Rules
-
The first character goes in row 0. Each following character goes one row lower until row
num_rows - 1
is reached, then one row higher until row 0 is reached, and the pattern repeats.
-
The output is row 0, then row 1, and so on through row
num_rows - 1
, with the characters of each row kept in their original order from
s
.
-
With
num_rows = 1
, every character is in row 0.
Constraints
-
1 <= len(s) <= 1000
-
s
consists of English letters (lowercase and uppercase),
','
and
'.'
.
-
1 <= num_rows <= 1000
Examples
Input: s = "PAYPALISHIRING", num_rows = 3
Output: "PAHNAPLSIIGYIR"
This is the pattern shown above. Row 0 holds P, A, H, N, row 1 holds A, P, L, S, I, I, G, and row 2 holds Y, I, R.
Input: s = "PAYPALISHIRING", num_rows = 4
Output: "PINALSIGYAHRPI"
On 4 rows the characters go down from P to the second P, back up through A and L to I, and so on. The rows read P I N, A L S I G, Y A H R and P I.
Input: s = "AB", num_rows = 1
Output: "AB"
With a single row there is no zigzag, so the string comes back unchanged.