2024-08-03 10:43阅读: 7评论: 0推荐: 0

力扣-6-Z 字形变换

其实叫“N 字形变换”更形象

第一版代码,在二维数组中模拟打印过程,但是时间和空间效率都很差,都是 n2

string convert(string s, int numRows) {
int len = s.size();
// 如果只有一行或者只有一列则直接输出
if (numRows == 1 || numRows >= len) return s;
// 计算每个周期占用的字符数量
int cycle = numRows + numRows - 2;
int column = (1 + numRows - 2) * len / cycle + len % cycle;
vector<string> maps(numRows, string(column, 0));
for (int x = 0, y = 0, k = 0; k < len; k++) {
maps[x][y] = s[k];
if (k % cycle + 1 < numRows) x++;
else {
x--;
y++;
}
}
string res;
for (string str : maps) for (char ch : str) if (ch)res += ch;
return res;
}

本文作者:YaosGHC

本文链接:https://www.cnblogs.com/yaocy/p/18340164

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   YaosGHC  阅读(7)  评论(0编辑  收藏  举报
历史上的今天:
2022-08-03 力扣-704-二分查找
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起