主要是一个Z字形状
0 10
1 911
2 8 12
3 7 13
46 14
5 15。。。。。这样一个形状
因为只需要横向顺序,所以横向压缩就好
上面变成这样
0, ,10
1,9,11
2,8,12
3,7,13
4,6,14
5, ,15
这样的话只需要把数组纵向存储然后空出奇数行首位并注意顺序即可
c# code
public class Solution
{
public string Convert(string s, int numRows)
{
if (numRows == 1 || s.Length <= numRows)
{
return s;
}
string ret = “”;
if (numRows == 2)
{
for (int i = 0; i < s.Length && 2 * i < s.Length; i++)
{
ret += s[2 * i];
}
for (int i = 0; i < s.Length && 2 * i + 1 < s.Length; i++)
{
ret += s[2 * i + 1];
}
}
else
{
char[,] c = new char[numRows, //s.Length % (numRows * 2 – 2) == 0 ? s.Length / (numRows * 2 – 2) :
(s.Length / (numRows * 2 – 2) + 1) * 2];
int q = numRows < 3 ? 1 : numRows – 1;
int index = 0, row = 0, col = 0;
while (index < s.Length)
{
if (col % 2 == 0)
{
for (row = 0; row < numRows && index < s.Length; row++)
{
c[row, col] = s[index];
index++;
}
col++;
}
else
{
for (row = numRows – 2; row > 0 && index < s.Length; row–)
{
c[row, col] = s[index];
index++;
}
col++;
}
}
for (int i = 0; i < c.GetLength(0); i++)
{
for (int j = 0; j < c.GetLength(1); j++)
{
if (c[i, j] != ‘\0’)
{
ret += c[i, j];
}
}
}
}
return ret;
}
}