将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下:
L C I R
E T O E S I I G
E D H N
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“LCIRETOESIIGEDHN”。请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
- Java按行排序
class Solution {
public String convert(String s, int numRows) {
if (numRows == 1) return s;
List<StringBuilder> rows = new ArrayList<>();
for (int i = 0; i < Math.min(numRows, s.length()); i++)
rows.add(new StringBuilder());
int curRow = 0;
boolean goingDown = false;
for (char c : s.toCharArray()) {
rows.get(curRow).append(c);
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown;
curRow += goingDown ? 1 : -1;
}
StringBuilder ret = new StringBuilder();
for (StringBuilder row : rows) ret.append(row);
return ret.toString();
}
}
2.C#利用二维数组
public class Solution {
public string Convert(string s, int numRows) {
if(numRows<=1||s.Length==1)
{
return s;
}
char[,] result = new char[numRows, (s.Length / (2*numRows-2) +1)*(numRows-1)];
int i = 0, j = 0;
for (int k = 0; k < s.Length; k++)
{
if(j%(numRows-1)==0)
{
result[i, j] = s[k];
if (i == numRows - 1)
{
j++;
i = 0;
}
else
{
i++;
}
}
else
{
result[numRows -1- j % (numRows-1), j] = s[k];
j++;
}
}
string resultString = "";
for (i = 0; i < result.GetLength(0); i++)
{
for (j = 0; j < result.GetLength(1); j++)
{
if (result[i, j] != '\0')
{
resultString += result[i, j];
}
}
}
return resultString;
}
}