題目:
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 RAnd 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)做除,可以區分當前是上升還是下降(偶數上升,奇數下降)。
代碼:
#include <string>
#include <numeric>
#include <vector>
using namespace std;
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());
}
};