6. Zigzag Conversion ๐
Difficulty: Medium
- Tags: String
, Simulation
Description
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
And then read line by line: "PAHNAPLSIIGYIR".
Write the code that will take a string and make this conversion given a number of rows.
Examples
Example 1:
Input:
Output:
Example 2:
Input:
Output:
Explanation:
Example 3:
Input:
Output:
Constraints
The input string
s
consists of printable ASCII characters.numRows
is an integer in the range [1, 1000].
Solution ๐ก
To solve this problem, we simulate the zigzag pattern by appending characters to each row based on their current position. We traverse the string s
and update the direction (up or down) when reaching the first or last row. After processing all characters, we concatenate the rows to get the final result.
Java
Time Complexity โณ
O(n): The time complexity is linear, where
n
is the length of the strings
.
Space Complexity ๐พ
O(n): The space complexity is also linear, as we are storing the zigzag pattern in a list of string builders.
You can find the full solution here.
Last updated