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"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
Example 3:
Input: s = "A", numRows = 1
Output: "A"
Constraints:
1 <= s.length <= 1000
s
consists of English letters (lower-case and upper-case), ','
and '.'
.1 <= numRows <= 1000
class Solution:
def convert(self, s: str, numRows: int) -> str:
index_dict = dict()
zigzag_index = 0
down = 1 # Down flag
up = -1 # Up flag
move = 0
for character in s:
if zigzag_index == 0: # Down
move = down
elif zigzag_index == numRows - 1: # Up
move = up
index_dict[zigzag_index] = index_dict.get(zigzag_index, '') + character
zigzag_index +=move # Move index
return ''.join(index_dict.values())
Time complexity :
numRows=4
P | A | Y | P | A | L | I | S | H | I | R | I | N | G |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 2 | 3 | 2 | 1 | 0 | 1 | 2 | 3 | 2 | 1 | 0 | 1 |
같은 인덱스(=같은 행)를 가진 문자끼리 문자열을 만들어서 오름차순 인덱스(행이 증가하도록)로 문자열 concat