题目:
将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
利用二维矩阵模拟
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string convert(string s, int numRows) {
int n = s.length(), r = numRows;//r是行数
if (r == 1 || r >= n) {
return s;
}
int t = r * 2 - 2;//t一回的的数量
int c = (n + t - 1) / t * (r - 1);
vector<string> mat(r, string(c, 0));
for (int i = 0, x = 0, y = 0; i < n; ++i) {//i遍历数组
mat[x][y] = s[i];
if (i % t < r - 1) {//r-1=3,要余数<3,代表是在下降阶段,余数>=3是在右上角阶段。
//跟我那个差不多,我那个要命名2个变量,更加耗费空间,这个余数的更简便
++x; // 向下移动
}
else {
--x;
++y; // 向右上移动
}
}
string ans;
for (auto& row : mat) {//遍历,如果空的就加空,这个挺有意思
for (char ch : row) {
if (ch) {
ans += ch;
}
}
}
/* string ans;
for (auto& row : mat) {
for (char ch : row) {
cout << ch << " " << endl;
if (ch) {
ans += ch;
}
}
cout << endl;
}*/
return ans;
}
};