6. Zigzag Conversion
Problem Statement
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)
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
Solutions
Push the characters into a vector of strings, one for each row. Use a direction flag to determine whether to move down or up the rows. When reaching the top or bottom row, reverse the direction.
- Time Complexity: O(n)
- Space Complexity: O(n)
Calculate the length of each zigzag segment and use it to determine the characters' positions in the output string. This method avoids using extra space for row strings.
- Time Complexity: O(n)
- Space Complexity: O(1)