【题目描述】The string"PAYPALISHIRING"is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line:“PAHNAPLSIIGYIR”
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert(“PAYPALISHIRING”, 3)should return"PAHNAPLSIIGYIR".
【解题思路】希望在一次迭代中完成对字符串的分组。而经过简单的分析,可以发现迭代的索引与分组的索引有非常规律的对应关系。
对(nRows-1)取余,可以区分行数。
对(nRows-1)做除,可以区分当前是上升还是下降(偶数上升,奇数下降)。
根据余数和整数就可以确定每一个字符所在的行数。
【考查内容】字符串
class Solution {
public:
string convert(string s, int numRows) {
// 判断行数是否大于1,字符串是否存在,否则直接输出
if (s.size() == 0 || numRows < 2)
return s;
// 创建字符串数组,用于存储每一行的字符串
vector<string> ret(numRows);
// 一次遍历
for (size_t i = 0; i < s.size(); i++){
// 利用numRows-1取余和取整
int m = i % (numRows - 1);
int n = i / (numRows - 1);
// 利用余数和整数判断当前字符在第几行,然后就存入相应行数的字符串中
(n & 0x1 ? ret[numRows - 1 - m] : ret[m]).push_back(s[i]);
}
// 将各个字符串按照行顺序进行叠加,得到最重要输出的字符串
return accumulate(ret.begin(), ret.end(), string());
}
};