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 2 3
P A H N A P L S I I G Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Example:
1 2 3 4 5 6 7 8 9 10 11
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"
Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation:
P I N A L S I G Y A H R P I
Analysis
ZigZag Simulation
Use extra numRows buckets to simulate the ZigZag process.
public String convert(String s, int numRows){ if (numRows == 1) { return s; } int n = s.length(); // buckets List<StringBuilder> sbList = new ArrayList<>(); for (int i = 0; i < numRows; ++i) { sbList.add(new StringBuilder()); } // simulation int row = 0, idx = 0; boolean goingDown = true; while (idx < n) { sbList.get(row).append(s.charAt(idx)); // update if (goingDown) row += 1; else row -= 1; // out-of-bound if (row > numRows - 1) { goingDown = false; row = (numRows - 1) - 1; } if (row < 0) { goingDown = true; row = 1; } count += 1; } // concatenate StringBuilder result = new StringBuilder(); for (StringBuilder sb : sbList) { result.append(sb); } return result.toString(); }
Time: $O(N)$ Space: $O(N)$
Visit by Row
By observation, consider the following cases:
Characters in row 0.
Characters in row numRows - 1.
Characters in inner rows.
Just analyze the examples below and find the rules for indexing. The index for inner rows is tricky and a bit complex. Try to think how to make the current row number contribute.