ZigZag Conversion
题目大意:
For example:The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
while convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”
我的想法、
创建nRows 的StringBuffers,然后使用java中的append()函数依次追加字符串;
代码、
public class Solution {
public String convert(String s, int numRows) {
char[] c = s.toCharArray(); //变成数组
int len = s.length();
StringBuffers[] sb = new StringBuffers[numRows]; //实例化对象sb
for(int i = 0; i < sb.length; i++)
sb[i] = new StringBuffers();
int i = 0;
while(i < len){
for(int j = 0; j < len && j<numRows; j++)
sb[j].append(c[i++]); //开始从上向下插入值
for(int j = numRows - 2; j < len && j > 0; j--) //注意此处的numRows-2
sb[j].append(c[i++]); //插入对角线方向的值
}
}
for(int i = 1; i < numRows; i++)
sb[0].append(sb[i]); //进行每一行的依次的插入并输出
return sb[0].toString; //按照字符串的方式读出
}