"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)P A H N A P L S I I G Y I R
Result: PQHNAPLSIIGYIR
If we think of the above as 2D matrix of letters, the key here is to figure out for each character of the string, what will be its row index and column index in the matrix? Once we have the 2D matrix, we can just go through it row by row to construct the output string.
In the above example, the number of row is 3. Then there will be 3-2=1 element between each multiple-element column. So if the string length is 4, 4/(3+(3-2))=1, there will be 1*(3-2+1) = 2 columns. If the string length is 5, 6, 7, there will be 1*(3-2+1) + 1 = 3 columns, if string length is 8, there will be 2*(3-2+1) = 4 columns.
Got the math?
And here is the code: