October 30, 2024
This one took me about 15 minutes to come up with a solution. I then worked through it with this naive solution.
1class Solution:2 def convert(self, s: str, numRows: int) -> str:3 grid = [['' for column in range(len(s))] for row in range(numRows)]4 x, y = 0, 05 direction = 16 for char in s:7 grid[y][x] = char8 if y == numRows - 1:9 direction = -110 x += 111 elif direction == -1 and y > 0:12 x += 113 elif direction == -1 and y == 0:14 direction = 115 y += direction if numRows > 1 else 016 result = ""17 for row in grid:18 for char in row:19 if char:20 result += char21 return result
O(n) = n*m or n^2
Looking back, I realized I didn't need to include the empty spaces as if it were illustrated. This allows me to simplify my code by using the append() method for lists. Here is my improved version:
1class Solution:2 def convert(self, s: str, numRows: int) -> str:3 if numRows == 1 or numRows >= len(s):4 return s56 grid = [[] for _ in range(numRows)]7 y = 08 direction = 19 for char in s:10 grid[y].append(char)11 if y == numRows - 1:12 direction = -113 elif y == 0:14 direction = 115 y += direction1617 for i in range(len(grid)):18 grid[i] = ''.join(grid[i])19 result = ''.join(grid)20 return result
LeetCode 12. Integer to Roman
LeetCode 28. Find the Index of the First Occurrence in a String