ZigZag
一、題解
給出字符串helloWorld!java
- 這是3行
從左往右依次是holelWrdlo!
- 這是4行
從左往右依次是hoeWrlol!ld
二、思路
每一行都是獨立的字符串,最後拼接起來就ok。
app
三、實現
一、n行即n個String,考慮到字符串常常拼接修改,故使用StringBuiler能大大提升效率。ui
StringBulier[] sb = new StringBuiler[n] //n行
二、觀察規律,發現4個一組(紅色框框部分)。
因而可知,咱們只需循環紅色部分便可。紅色部分包含兩部分:左側n個,右側n-2個。
每個紅框部分以下:
spa
for (int i = 0; i < n; i++) { //左側依次加入String1,String2,...String n sb[i].append(字符串中下標爲i對應的字符即str.charAt(i)) } for (int i = n - 2; i > 0 ; i--) { // 從下往上因此要倒着來 // 右側依次加入String1,String2,...String n sb[i].append(字符串中下標爲i對應的字符即str.charAt(i)) }
三、循環紅色框框部分便可3d
int index = 0; //對應字符串的下標 while(index < length){ //length爲字符串長度 //循環紅色框框部分 }
四、細節指針
一、若是傳入hello,可是行數比字符串長度還大好比1000行,顯然結果仍是hello。 二、若是傳入了null或空,則直接返回null或者空。 三、有這樣一種狀況:如圖。 開始第四次循環紅框部分時,此時index=13,知足index<length條件。 若是index=16時,它還在while內部循環,此時str.charAt(index)就會拋出空指針異常! 因此在while內部的for循環也要加上index<length的條件。
四、Java代碼
若有意見,多多指出!code
public String convert(String text, int nRows) { if (nRows < 1) return null; if (null == text || "".equals(text)) return text ; if (text.length() <= nRows || nRows == 1) return text; char[] chars = text.toCharArray(); int len = chars.length; StringBuilder[] sb = new StringBuilder[nRows]; for (int i = 0; i < sb.length; i++) { sb[i] = new StringBuilder(); } int charIndex = 0; while (charIndex < len) { for (int i = 0; i < nRows && charIndex < len; i++) { sb[i].append(chars[charIndex++]); } for (int i = nRows - 2; i > 0 && charIndex < len; i--) { sb[i].append(chars[charIndex++]); } } StringBuilder res = new StringBuilder(); for (int i = 0; i < sb.length; i++) { res.append(sb[i]); } return res.toString(); }