1
+ # Runtime: 96 ms (Top 61.23%) | Memory: 14 MB (Top 75.15%)
1
2
class Solution :
2
3
def convert (self , s : str , numRows : int ) -> str :
3
-
4
+
4
5
# safety check to not process single row
5
6
if numRows == 1 :
6
7
return s
7
-
8
+
8
9
# safety check to not process strings shorter/equal than numRows
9
10
if len (s ) <= numRows :
10
11
return s
11
-
12
+
12
13
# safety check to not process double rows
13
14
if numRows == 2 :
14
15
# slice every other character
15
16
return s [0 ::2 ] + s [1 ::2 ]
16
-
17
+
17
18
# list that stores the lines
18
19
# add lines with initial letters
19
20
lines : list [str ] = [letter for letter in s [:numRows ]]
20
-
21
+
21
22
# positive direction goes down
22
23
# lines are created, so it's going up
23
24
direction : int = - 1
24
-
25
+
25
26
# track the position at which the letter will be added
26
27
# position after bouncing off, after adding initial lines
27
28
line_index : int = numRows - 2
28
-
29
+
29
30
# edge indexes
30
31
# 0 can only be reached by going up
31
32
# numRows only by going down
32
33
edges : set [int ] = {0 , numRows }
33
-
34
+
34
35
for letter in s [numRows :]:
35
36
# add letter at tracked index position
36
37
lines [line_index ] += letter
37
-
38
+
38
39
# prepare index before next loop iteration
39
40
line_index += direction
40
-
41
+
41
42
# reaching one of the edges
42
43
if line_index in edges :
43
44
# change direction
44
45
direction = - direction
45
46
# bounce off if bottom edge
46
47
if line_index == numRows :
47
48
line_index += direction * 2
48
-
49
- return "" .join (lines )
49
+
50
+ return "" .join (lines )
0 commit comments