题意:给出一个字符串和行数,求字符串zigzag变换后的字符串
如PAYPALISHIRING和行数为3,zigzag形式为
P A H N A P L S I I G Y I R
即结果字符串为PAHNAPLSIIGYIR
思路:用n个字符串,依次填充,然后合并
代码如下:
class Solution {
public String convert(String s, int numRows)
{
if (numRows == 1) return s;
StringBuilder[] sb = new StringBuilder[numRows];
for (int i = 0; i < numRows; i++)
{
sb[i] = new StringBuilder();
}
int step = 1;
int index = 0;
for (int i = 0; i < s.length(); i++)
{
sb[index].append(s.charAt(i));
if (index == numRows - 1) step = -1;
else if (index == 0) step = 1;
index += step;
}
StringBuilder res = new StringBuilder();
for (int i = 0; i < numRows; i++)
{
res.append(sb[i]);
}
return res.toString();
}
}