1 public String convert(String s, int numRows) { 2 if (s == null || numRows == 1) { 3 return s; 4 } 5 6 //每行一个StringBuilder对象 7 List<StringBuilder> list = new ArrayList<>(); 8 for (int i = 0; i < Math.min(s.length(), numRows); i++) { 9 list.add(new StringBuilder()); 10 } 11 12 boolean down = false; 13 int row = 0; 14 //遍历字符串,一次顺序放入一行,但是在首末两行判断转向即可 15 for (int i = 0; i < s.length(); i++) { 16 if (row == 0 || row == list.size() - 1) { 17 down = !down; 18 } 19 list.get(row).append(s.charAt(i)); 20 row += (down ? 1 : -1); 21 } 22 String res = ""; 23 for (StringBuilder sb : list) { 24 res += sb.toString(); 25 } 26 return res; 27 }