public String convert(String str, int numRows){ if (numRows == 1){ return str; } StringBuffer stringBuffer = new StringBuffer(); for (int i=0; i<numRows; i++){ if ((str.length()-1) >= i) { stringBuffer.append(str.charAt(i)); }
int index = i; while ((str.length()-1) >= (index+numRows+(numRows-2))){ // 首行 && 尾行 // 注意边界值 if ((index+numRows+(numRows-2) > (index+numRows+(numRows-2)-i-i)) && ((index+numRows+(numRows-2)-i-i) > index) ){ stringBuffer.append(str.charAt(index+numRows+(numRows-2)-i-i)); } stringBuffer.append(str.charAt(index + numRows + (numRows - 2))); index = index+numRows+(numRows-2); }
publicstatic String conv(String str, int row){ StringBuffer[] sbArr = new StringBuffer[row]; for (int i=0; i<row; i++){ sbArr[i] = new StringBuffer(); } int i = 0; while (i < str.length()){ for (int rowIndex=0;rowIndex<row && i<str.length();rowIndex++){ sbArr[rowIndex].append(str.charAt(i++)); } for (int rowIndex=row-2;rowIndex>=1 && i<str.length(); rowIndex--){ sbArr[rowIndex].append(str.charAt(i++)); } } for (int r=1; r<row; r++){ sbArr[0].append(sbArr[r]); } return sbArr[0].toString(); }