//Z 字形变换:
//将字符串 "PAYPALISHIRING" 以 Z 字形排列成给定的行数:
//
//P A H N
//A P L S I I G
//Y I R
//之后按逐行顺序依次排列:"PAHNAPLSIIGYIR"。编写一个函数,输入字符串和行数 numRows,
//返回以 Z 字形排列的字符串。
// 例如,输入字符串 "PAYPALISHIRING" 和 numRows = 3,返回 "PAHNAPLSIIGYIR"。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
string convert(string s, int numRows) {
if (numRows == 1) return s; // 当 numRows 为 1 时,直接返回原字符串
vector<string> rows(min(numRows, int(s.size()))); // 创建 numRows 个字符串,存储每行的字符
int curRow = 0; // 当前所在行
bool goingDown = false; // 标记是否向下走
for (char c : s) {
rows[curRow] += c; // 将当前字符添加到对应行
if (curRow == 0 || curRow == numRows - 1) goingDown = !goingDown; // 当到达 Z 字形转折点时改变方向
curRow += goingDown ? 1 : -1; // 根据方向更新行数
}
string result;
for (string& row : rows) {
result += row; // 将每行字符串拼接起来
}
return result;
}
int main() {
string s = "PAYPALISHIRING";
int numRows = 3;
cout << convert(s, numRows); // 输出转换后的字符串
return 0;
}