table of Contents
Title description
Arrange a given character string in a zigzag pattern from top to bottom and from left to right according to a given number of lines. For example, when the input string is LEETCODEISHIRING and the number of rows is 3, the arrangement is as follows:
L C I R
E T O E S I I G
E D H N
After that, your output needs to be read line by line from left to right, resulting in a new string: LCIRETOESIIGEDHN
solution
Use simulation method to solve vivid image.
Assuming that the number of rows is n, we generate n lists to represent n rows, and define a pointer variable to simulate the zigzag trend: go down from the first row in turn, go up after reaching the last row, repeat the loop until all elements are It is traversed.
Each time the pointer variable reaches an element, the element is inserted into the list of the corresponding number of rows. Finally, each line of characters is connected and output to get the desired result.
Complexity analysis: Because it only needs to traverse the string once, the time complexity is . Only a constant number of variables need to be defined, so the space complexity is .
Code
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
pool = [list() for i in range(numRows)]
down = False
pool_index = 0
for char in s:
if pool_index == numRows - 1 or pool_index == 0:
down = not down
pool[pool_index].append(char)
if down:
pool_index += 1
else:
pool_index -= 1
result = "".join(["".join(element) for element in pool])
return result
Code walkthrough
class Solution:
def convert(self, s: str, numRows: int) -> str:
// 如果给定的行数只有1行,那么只需要将原字符串返回
if numRows == 1:
return s
// 定义存储每一行字符的二维列表
pool = [list() for i in range(numRows)]
// down变量用来定义此时模拟Z字型游标指针的走向(False为向上,True为向下)
down = False
// 游标指针变量,表示当前所在的行数
pool_index = 0
for char in s:
// 如果游标抵达边界,需要改变方向
if pool_index == numRows - 1 or pool_index == 0:
down = not down
// 对应行添加字符
pool[pool_index].append(char)
if down:
pool_index += 1
else:
pool_index -= 1
// 按照每一行字符依次拼接的方式输出结果
result = "".join(["".join(element) for element in pool])
return result
// 自测用例
if __name__ == '__main__':
s = Solution()
result = s.convert("LEETCODEISHIRING", 3)
print(result)