1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { public String convert(String s, int numRows) { if (numRows == 1 || s.length() <= numRows) return s;
StringBuilder[] rows = new StringBuilder[numRows]; for (int i = 0; i < numRows; i++) { rows[i] = new StringBuilder(); }
int currentRow = 0; boolean goingDown = false;
for (char c : s.toCharArray()) { rows[currentRow].append(c);
if (currentRow == 0 || currentRow == numRows - 1) { goingDown = !goingDown; }
currentRow += goingDown ? 1 : -1; }
StringBuilder result = new StringBuilder(); for (StringBuilder row : rows) { result.append(row); }
return result.toString(); } }
|