0
点赞
收藏
分享

微信扫一扫

[leetcode]Z 字形变换

秦瑟读书 2024-05-03 阅读 7

. - 力扣(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;
    }
};

举报

相关推荐

Z 字形变换

【Z字形变换】

Z字形变换

LeetCode-006-Z 字形变换

0006 - Z字形变换

0 条评论