将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。
比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:
P A H N
A P L S I I G
Y I R
之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。
请你实现这个将字符串进行指定行数变换的函数:
string convert(string s, int numRows);
示例 1:
输入:s = "PAYPALISHIRING", numRows = 3
输出:"PAHNAPLSIIGYIR"
示例 2:
输入:s = "PAYPALISHIRING", numRows = 4
输出:"PINALSIGYAHRPI"
解释:
P I N
A L S I G
Y A H R
P I
示例 3:
输入:s = "A", numRows = 1
输出:"A"
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/zigzag-conversion
方法1:string数值存储
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string convert(string s, int numRows) {
int n = numRows;
vector<string> a(n);//存字符串的数组
int fx = 0;
int flag = -1;//到达位置的纵坐标
for (int i = 0; i < s.size(); i++) {
if (fx < n)
{
flag++;
}
else if (fx < 2 * n - 1)
{
flag--;
}
if (fx == 2 * n - 2) {
fx = 0;
}
fx++;
string get = a[flag];
//加上去
get = get + s[i];
a[flag] = get;
cout << get << endl;
}
string end = "";
for (int i = 0; i < a.size(); i++) {
end = end + a[i];
}
return end;
}
};
方法2利用二维矩阵模拟
#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;
}
};
方法3压缩矩阵空间
//压缩矩阵空间
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string convert(string s, int numRows) {
int n = s.length(), r = numRows;
if (r == 1 || r >= n) {
return s;
}
vector<string> mat(r);
for (int i = 0, x = 0, t = r * 2 - 2; i < n; ++i) {
mat[x] += s[i];
i% t < r - 1 ? ++x : --x;// 在|/的拐角处,左边是x++,右边是x--
}
string ans;
for (auto& row : mat) {
ans += row;
}
return ans;
}
};
方法4直接构造
//压缩矩阵空间
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
string convert(string s, int numRows) {
int n = s.length(), r = numRows;//n是s数量,r是行数
if (r == 1 || r >= n) {//为什么要加这个
return s;
}
string ans;
int t = r * 2 - 2;//t值一个周期,一个周期是“|/”
for (int i = 0; i < r; ++i) { // 枚举矩阵的行
for (int j = 0; j + i < n; j += t) { // 枚举每个周期的起始下标 每个a[0]
ans += s[j + i]; // 当前周期的第一个字符
if (0 < i && i < r - 1 && j + t - i < n) {//0 < i && i < r - 1是找到在中间的行,一周期有两个数
ans += s[j + t - i]; // 当前周期的第二个字符,t-i是位置,t-1是第1行,t-2是第2行
//这里是插入“|/”里面的“/”上面的数
//难在对下标的处理上面
}
}
}
return ans;
}
};