这题是周六在石家庄等飞机时做的,boarding之前还NM在调试。。当时题目理解就错了,不知道它说的zigzag其实是下面的意思:
/*n=numRows
Δ=2n-2 1 2n-1 4n-3
Δ= 2 2n-2 2n 4n-4 4n-2
Δ= 3 2n-3 2n+1 4n-5 .
Δ= . . . . .
Δ= . n+2 . 3n .
Δ= n-1 n+1 3n-3 3n-1 5n-5
Δ=2n-2 n 3n-2 5n-4
*/
理解了的话,代码这样写:
public String convert(String s, int nRows) {
if (nRows == 0 || nRows == 1) return s;
StringBuilder[] sb = new StringBuilder[nRows];
for (int i = 0; i < nRows; i++) sb[i] = new StringBuilder();
int i = 0;
while (i < s.length()) {
for (int row = 0; row < nRows && i < s.length(); row++) {
sb[row].append(s.charAt(i++));//vertically down
}
for (int row = nRows - 2; row > 0 && i < s.length(); row--) {
sb[row].append(s.charAt(i++));//obliquely up
}
}
for (int j = 1; j < nRows; j++) {
sb[0].append(sb[j]);
}
return sb[0].toString();
}