将一个给定字符串根据给定的行数,以从上往下、从左到右进行 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);
示例 1:
输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"
示例 2:
输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解释:
L D R
E O E I I
E C I H N
T S G
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zigzag-conversion
JavaScript方法:
var convert = function(s, numRows) {
if(numRows < 2) return s;
let r = Array(numRows).fill(""),
c = (numRows - 1) * 2;
s.split("").forEach((l, i) => r[i % c < numRows ? i % c : c - i % c] += l);
return r.join("")
};
C#方法:
public string Convert(string s,int numRows) {
if (numRows == 1)
return s;
int temp = 2 * numRows - 3;
char[] a = new char[s.Length];
int count = 0;
char tempChar ;
int indexCur = 0;
int indexCur1 = 0;
int top = 0;
for (int i = 0; i < numRows; i++)
{
if (i >= s.Length)
continue;
indexCur = i;
top = 0;
tempChar = s[i];
indexCur = i;
while (true)
{
a[count++] = tempChar;
if (top == 0)
{
top = 1;
if (numRows - i != 1)
indexCur += temp - i * 2 + 1;
else
indexCur += (temp - (numRows - 1 - i) * 2) + 1;
}
else
{
top = 0;
if(numRows - i == numRows)
indexCur += temp - i * 2 + 1;
else
indexCur += (temp - (numRows -1 - i) * 2) + 1;
}
if (indexCur >= s.Length|| indexCur== indexCur1)
break;
indexCur1 = indexCur;
tempChar = s[indexCur];
}
}
return string.Join("",a);
解决思路:按行排序,对字符串遍历,每行一次插入相应的字符。通过构造一个与字符串长度相等的数组 chars 用于存储转换后的字符顺序。构建一个长度为numRows的数组存储每一行下一次的插入下标。计算初始下标之后。依次插入字符即可