ZigZag ConVersion
问题描述:给定行的个数,字符串”PAYPALISHIRING”以zigzag的模式被打印出来,具体如下:
P A H N
A P L S I I G
Y I R
但是,需要按照PAHNAPLSIIGYIR
的形式来读出。
也就是说,定义一个函数:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3)
应该返回PAHNAPLSIIGYIR
。
问题解决:
public String convert(String s, int nRows) {
char[] c = s.toCharArray();
int len = c.length;
StringBuffer[] sb = new StringBuffer[nRows];
for (int i = 0; i < sb.length; i++) sb[i] = new StringBuffer();
int i = 0;
while (i < len) {
for (int idx = 0; idx < nRows && i < len; idx++) // vertically down
sb[idx].append(c[i++]);
for (int idx = nRows-2; idx >= 1 && i < len; idx--) // obliquely up
sb[idx].append(c[i++]);
}
for (int idx = 1; idx < sb.length; idx++)
sb[0].append(sb[idx]);
return sb[0].toString();
}
采用空间换时间的策略,使用了nRows个StringBuffer。