=============================Python==========================
class Solution: def convert(self, s: str, numRows: int) -> str: res = ['' for _ in range(numRows)] i = 0 while i < len(s): j = 0 while i < len(s) and j < numRows: res[j] += s[i] i += 1 j += 1 k = numRows - 2 while i < len(s) and k > 0: res[k] += s[i] i += 1 k -= 1 ans = '' for i in res: ans += i return ans
==============================Java===========================
class Solution { public String convert(String s, int numRows) { if (numRows == 1) return s; List<StringBuilder> rows = new ArrayList<>(); for (int i = 0; i < Math.min(numRows, s.length()); i++){ rows.add(new StringBuilder()); } int curRow = 0; boolean goingDown = false; for (char c : s.toCharArray()) { rows.get(curRow).append(c); if (curRow == 0 || curRow == numRows - 1) { goingDown = !goingDown; } curRow += goingDown ? 1 : -1; } StringBuilder ret = new StringBuilder(); for (StringBuilder row : rows) ret.append(row); return ret.toString(); } }