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:
Example 1:
Example 2:
Example 3:
Constraints:
1 <= s.length <= 1000
s
consists of English letters (lower-case and upper-case), ','
and '.'
.1 <= numRows <= 1000
Note: In the following rules, we can return the input string as the answer:
We created a table to simulate the behavior.
Example:
Step 1
Put each character into the table:
P | A | H | N | |||
---|---|---|---|---|---|---|
A | P | L | S | I | I | G |
Y | I | R |
Step 2
Go through the table line by line, remove the space character on the line.
It would look like:
P | A | H | N | |||
---|---|---|---|---|---|---|
A | P | L | S | I | I | G |
Y | I | R |
Step 3
Finally, concatenate all of the lines to get the answer: PAHNAPLSIIGYIR
Refer to solution 1, using the index instead, and find the distance between two characters in the same row. Then, we get every character via jump the index.
Example:
Step 1
Put each character into the table:
P | I | N | ||||
---|---|---|---|---|---|---|
A | L | S | I | G | ||
Y | A | H | R | |||
P | I |
Step 2
Find the distance between the characters on each row:
Get each character by jumping the index column by column on each row.
The Formulas:
To simplify the code, both the first row and the last row which has two same distance values(two 6s).
Step 3
Convert the character using the index instead:
0 | 6 | 12 | ||||
---|---|---|---|---|---|---|
1 | 5 | 7 | 11 | 13 | ||
2 | 4 | 8 | 10 | |||
3 | 9 |
Go through every row to collect the characters via index jumping.
The answer is PINALSIGYAHRPI.See the full solution.
leetcode
Medium
String