LeetCode05-Z型打印

就是给定一个字符串,然后按写竖着的 「z」的方式排列字符,就是下边的样子。

解法一
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| class Soultion{ public String convert(String s,int numberRows){ if(numberRows==1){ return s; } List<StringBuilder> list =new ArrayList<>(); for(int i =0;i<Math.min(numberRows,s.length());i++){ list.add(new StringBuilder()); } int curRow=0; boolean goDown =false; for(int i=0; i<s.length();i++){ list.get(curRow).append(s.charAt(i)); if(curRow == 0|| curRow == numberRows-1 ){ goDown =!goDown; } curRow += goDown?1:-1; } String needStr=""; for(StringBuilder sb: list){ needStr += sb.toString(); } return needStr; } }
|
__END__