原题:https://leetcode-cn.com/problems/zigzag-conversion/
法一:直接模拟法
以一竖一斜为一个周期,周期t=r+r-2
用二维数组记录模拟数组再读取输出
class Solution {
public:
string convert(string s, int numRows) {
int n = s.size(), r = numRows;
if(numRows == 1 || r >= n) return s;
int t = 2 * r - 2;
int col = (n + t - 1) / t * (r - 1); // n/t向上取整
vector<string> mat(r, string(col, 0));
for(int i = 0, x = 0, y = 0;i < n;i++) {
mat[x][y] = s[i];
if(i % t < r - 1) {
x++;
}
else {
x--;
y++;
}
}
string ans;
for (auto &row : mat) {
for (char ch : row) {
if (ch) {
ans += ch;
}
}
}
return ans;
}
};
注意计算列col值时的计算顺序,否则容易超时
法二:模拟优化
模拟的二维数组中有许多空闲位置造成了浪费,用一维数组模拟降低消耗。
class Solution
{
public:
string convert(string s, int numRows)
{
if (numRows == 1)
{
return s;
}
int sSize = int(s.size());
int storeSize = min(sSize, numRows);
string result;
vector<string> store(storeSize);
int loc = 0;
//初始有一次更改change值,因此初始值为false
bool change = false;
for (int index = 0; index < sSize; index++)
{
store[loc].push_back(s[index]);
if (loc == numRows - 1 || loc == 0)
{
change = !change;
}
loc += change ? 1 : -1;
}
for (int index = 0; index < storeSize; index++)
{
result = result + store[index];
}
return result;
}
};