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)
1 | P A H N |
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
1 | string convert(string s, int numRows); |
Example 1:
1 | Input: s = "PAYPALISHIRING", numRows = 3 |
Example 2:
1 | Input: s = "PAYPALISHIRING", numRows = 4 |
The means of the problem is to place the original string to make it looks like connected “NNNN…”
As you can see from the graph, a vertical line and a diagonal line form a cycle.
So we can simulate the order of the place order. Store them in a matrix and then combine the answer string.
First we start from the vertical line. There is numRows
elements in the vertical line. We put the adjacent characters in original order in the line.
Then we fill the diagonal line. From the left bottom corner to the right top corner, and there is numRows - 2
elements in the diagonal line.
1 | class Solution { |