将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 “LEETCODEISHIRING” 行数为 3 时,排列如下:
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:“LCIRETOESIIGEDHN”。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入: s = “LEETCODEISHIRING”, numRows = 3
输出: “LCIRETOESIIGEDHN”
示例 2:
输入: s = “LEETCODEISHIRING”, numRows = 4
输出: “LDREOEIIECIHNTSG”
解释:
如果是首尾两行,那么就是对应原字符串中的2numRows-2;
如果是中间的,那么就对应 j + 2numRows-2 - 2*i,j对应的是前一个不是中间数字(之中间的斜线)的数字下标,i对应的是当前行数
class Solution {
public:
string convert(string s, int numRows) {
string convert_s = "";
int length_s = s.size();
if(numRows <=1)
return s;
int door = 2 * numRows - 2;//控制取数字的间隔
for (int i = 0; i < numRows;i++)//控制行数
{
for (int j = i; j < length_s;j+=door)
{
convert_s += s[j];
int k = j + door - 2 * i;//取中间斜线的数字并判断
if (i != 0 && i!= numRows-1 && k < length_s)
{
convert_s += s[k];
}
}
}
return convert_s;
}
};