Problem
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:
|
|
OR
Given a string and a number of lines k
, print the string in zigzag form. In zigzag, characters are printed out diagonally from top left to bottom right until reaching the kth line, then back up to top right, and so on.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Create String Array for Each Row
We can break each row into Strings and club them in the end. In java, we use StringBuilder to do that. Here is the gist:
Let n
be numRows
.
- Create an array of n strings,
sb[n]
- Now start traversing vertically down from 0th row to nth row.
- Then we come up vertically n-2 rows.
- Keep on doing 2 and 3 till we are at end of of string.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the length of the input strings
. - 🧺 Space complexity:
O(n)
wheren
is the length of the input strings
.