一 问题描述
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
二 算法简析
1.变换规则是Z字形变换,是由下至上,然后右下至上,一下一上为一个周期,循环迭代,如下所示:

2.设计二维表std::vector<std::vector<char> >z_array存储变换后的字符串,z_array第一维度是numRows,第二维度存储对应的字符串,如以上每个字符对应的下标是:

则z_array存储为
z_array[0] (1,1)(2,1)(3,1)对应的字符
z_array[1] (2,1)(2,2)(2,3)(2,4) (2,5) (2,6) (2,7)对应的字符
z_array[2] (3,1)(3,3)(3,5)对应的字符
3.将z_array输出成字符串
三 代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string convert(string s, int numRows) {
if (numRows <= 1) {
return s;
}
int row = 0;
bool switch_flag = true;
int size = s.size();
std::vector<std::vector<char> >z_array;
z_array.resize(numRows);
for (int k = 0;k < size;) {
z_array[row].emplace_back(s[k++]);
if (switch_flag && (numRows - 1 == row)) {
switch_flag = false;
}
if (!switch_flag && (0 == row)) {
switch_flag = true;
}
if (switch_flag) {
row++;
}
else {
row--;
}
}
std::string rs;
for (int loop = 0;loop < numRows;++loop) {
size = z_array[loop].size();
if (size > 0) {
rs.append(&z_array[loop][0], size);
}
}
return rs;
}
};
int main() {
Solution ss;
std::cout << ss.convert("LEETCODEISHIRING", 3) << std::endl;
return 0;
}
https://github.com/wangzhicheng2013/leetcode/tree/main/leetcode/Z%20%E5%AD%97%E5%BD%A2%E5%8F%98%E6%8D%A2