将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:

之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入: s = "LEETCODEISHIRING", numRows = 3
输出: "LCIRETOESIIGEDHN"
示例 2:
输入: s = "LEETCODEISHIRING", numRows = 4
输出: "LDREOEIIECIHNTSG"
解释:

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/zigzag-conversion
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这个题规律很明显。直接分析出每一行有哪些序号要取出来即可。

只要没有超出范围每行要取的元素:其中k=0,1,2,3...
首行:(2n-2)*k
中间行:(2n-2)*k+i和(2n-2)*k-i
末行:(2n-2)*k+n
用我的代码思路要注意将n=1的情况单独取出来(因为2n-2=0)。
class Solution {
public:
string convert(string s, int numRows) {
if(numRows==1) return s;//n=1单独考虑,直接返回就是答案
int len=s.length();
string ans="";//用于string加法存结果,可能有更好的做法吧
int cur=0;
int cst=2*numRows-2;//2n-2,恒定值
//处理首行
while(cur<len)//(2n-2)*k没有超过s的长度则放入结果中
{
ans+=s.substr(cur,1);
cur+=cst;
}
for(int i=1;i<numRows-1;i++)//处理中间行
{
cur=0;
while(cur+i<len)
{
ans+=s.substr(cur+i,1);
if(cur+cst-i<len) ans+=s.substr(cur+cst-i,1);
cur+=cst;
}
}
//处理末行
cur=numRows-1;
while(cur<len)
{
ans+=s.substr(cur,1);
cur+=cst;
}
return ans;
}
};
原文:https://www.cnblogs.com/xiying159/p/11740979.html