6. ZigZag Conversion
StringBuffer类可以append reverse insert deleteCharAt setCharAt
其实直接用String的array也ok
1 //New 这个方法挺好 i控制遍历,两个循环分别控制放哪里 2 3 int i = 0; 4 while (i < len) { 5 for (int idx = 0; idx < nRows && i < len; idx++) // vertically down 6 sb[idx].append(c[i++]); 7 for (int idx = nRows-2; idx >= 1 && i < len; idx--) // obliquely up 8 sb[idx].append(c[i++]); 9 } 10 11 //Old 12 class Solution { 13 public String convert(String s, int numRows) { 14 if(s == null || s.length() == 1 || s.length() == 0 || s.length() == 2 || numRows == 1) return s; 15 char[] str = s.toCharArray(); 16 HashMap<Integer, String> map = new HashMap<>(); 17 for(int i = 0; i < str.length; i++) { 18 int key = i % (2*numRows - 2); 19 if(key > numRows - 1) { 20 key = (2*numRows - 2) - key; 21 } 22 if(!map.containsKey(key)) { 23 map.put(key, ""); 24 } 25 map.put(key, map.get(key) + str[i]); 26 } 27 String res = ""; 28 for(int i = 0; i < numRows; i++) { 29 if(map.get(i) != null) { //numRows超过string长度的时候 map中可能出现null 所以要判断 30 res = res + map.get(i); 31 } 32 } 33 return res; 34 } 35 }