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 HN 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:
1
stringconvert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
publicclassSolution{ public String convert(String s, int numRows){ if (s == null || s.length() < 2 || numRows < 2){return s;} int numCols = (s.length() / (numRows + numRows - 2) + 1) * (1 + numRows - 2);
char[][] grids = newchar[numRows][numCols]; for (int i = 0; i < s.length(); i++){ int row = i % (numRows + numRows - 2); int col = i / (numRows + numRows - 2) * (1 + numRows - 2); if (row >= numRows){ col += row % (numRows - 1); row = (numRows - 1 - row) + numRows - 1; } grids[row][col] = s.charAt(i); }
StringBuffer res = new StringBuffer(); for (int i = 0; i < grids.length; i++){ for (int j = 0; j < grids[0].length; j++){ if (grids[i][j] != '\u0000'){res.append(grids[i][j]);} } } return res.toString(); } }