leetcode 6.
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)
P A H N A P L S I I G Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
should return "PAHNAPLSIIGYIR"
.
Solution. An awesome solution is from this post. Basically, it uses a StringBuffer array to build vertical and oblique parts. Let’s say string is “PAHNAPLSIIGYIR” with 4 rows. And we have StringBuffer[] sbs
sbs[0] P I N sbs[1] A L S I G sbs[2] Y A H R sbs[3] P I
In this way, to build vertical columns PAYP and ISHI, we can use below code:
for (int idx = 0; idx < numRows && i < len; idx++) { // build vertical part sbs[idx].append(s.charAt(i)); }
In order to build oblique columns AL and RI, we can use below code:
for (int idx = numRows - 2; idx >= 1 && i < len; idx--) { // build oblique part sbs[idx].append(s.charAt(i)); }
In the end, we concatenate the sbs[] array to get the result.
public static String convert(String s, int numRows) { StringBuffer[] sbs = new StringBuffer[numRows]; for (int i = 0; i < numRows; i++) { sbs[i] = new StringBuffer(); } int i = 0, len = s.length(); while (i < len) { for (int idx = 0; idx < numRows && i < len; idx++, i++) { // build vertical part sbs[idx].append(s.charAt(i)); } for (int idx = numRows - 2; idx >= 1 && i < len; idx--, i++) { // build oblique part sbs[idx].append(s.charAt(i)); } } for (int j = 1; j < numRows; j++) { sbs[0].append(sbs[j]); } return sbs[0].toString(); }
Check my code on github.