题目
将字符串 "PAYPALISHIRING" 以Z字形排列成给定的行数:
P A H N
A P L S I I G
Y I R
之后从左往右,逐行读取字符:"PAHNAPLSIIGYIR"
实现一个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入: s = "PAYPALISHIRING", numRows = 3
输出: "PAHNAPLSIIGYIR"
示例 2:
输入: s = "PAYPALISHIRING", numRows = 4
输出: "PINALSIGYAHRPI"
解释:
P I N
A L S I G
Y A H R
P I
思路
用min(numRows, int(s.size()))来定义Z形的行数;定义变量currentRows 用作当前行,当当前行触碰到最上行和最下行时,反向赋值。
/**第一次写代码将goingDown = !goingDown; 写成了goingDown != goingDown;,导致程序错误**/
if (numRows == 1) return s;
vector<string> newRows(min(numRows, int(s.size())));
int currentRows = 0;
bool goingDown = false;
for(char eve : s)
{
newRows[currentRows] += eve;
if (currentRows == 0 || currentRows == numRows - 1) goingDown = !goingDown;
currentRows += goingDown ? 1 : -1;
}
string res;
for (string newRow : newRows) res += newRow;
return res;
网友评论