[leetcode]Z 字形变换

. - 力扣(LeetCode)

class Solution {
public:
    string convert(string s, int numRows) {
        int n = s.length(), r = numRows;
        if (r == 1 || r >= n) {
            return s;
        }
        int t = r * 2 - 2;
        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) {
            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;
    }
};

相关推荐

  1. Z字形变换

    2024-05-04 04:14:01       20 阅读
  2. Leetcode-06-Z字形变换

    2024-05-04 04:14:01       19 阅读
  3. leetCode算法—6. N 字形变换

    2024-05-04 04:14:01       45 阅读
  4. 【算法题】6. N字形变换

    2024-05-04 04:14:01       41 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-04 04:14:01       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-04 04:14:01       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-04 04:14:01       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-04 04:14:01       18 阅读

热门阅读

  1. 代码随想录算法训练营第四十一天

    2024-05-04 04:14:01       16 阅读
  2. Delphi10和12的FDConnection1.GetTableNames参数不一样了

    2024-05-04 04:14:01       11 阅读
  3. 系统架构师英文题目

    2024-05-04 04:14:01       12 阅读
  4. grpc stream发送

    2024-05-04 04:14:01       12 阅读
  5. js中对象转数组常用的方法

    2024-05-04 04:14:01       11 阅读
  6. 嵌入式硬件中优化设计PCB提高焊接质量方法

    2024-05-04 04:14:01       11 阅读
  7. 【LAMMPS学习】八、基础知识(5.6)绝热核/壳模型

    2024-05-04 04:14:01       12 阅读
  8. R语言相关知识点

    2024-05-04 04:14:01       9 阅读
  9. k8s: 从私有仓库harbor获取镜像

    2024-05-04 04:14:01       10 阅读