题目
思路
模拟 Z 字形排列:创建一个大小为 numRows 的字符串数组,用于存储每一行的字符。使用一个指针 currentRow 表示当前字符应该放在哪一行。使用变量 goingDown 表示当前是向下移动还是向上移动,将每个字符放入对应的行,当 currentRow 到达第一行或最后一行时,改变移动方向。最后将每一行的字符按顺序拼接成最终的结果字符串。
#include <string>
#include <vector>
#include <algorithm>
class Solution {
public:
string convert(string s, int numRows) {
if (numRows == 1) return s; // 如果只有一行,直接返回原字符串
vector<string> rows(min(numRows, int(s.size()))); // 创建行数组
int currentRow = 0; // 当前行
bool goingDown = false; // 移动方向
for (char c : s) {
rows[currentRow] += c; // 将字符放入当前行
// 如果到达第一行或最后一行,改变移动方向
if (currentRow == 0 || currentRow == numRows - 1) {
goingDown = !goingDown;
}
// 更新当前行
currentRow += goingDown ? 1 : -1;
}
string result;
for (string row : rows) {
result += row; // 逐行拼接结果
}
return result;
}
};