LeetCode 6. Z 字形变换

题目描述

6. Z 字形变换

image-20230311200513009

image-20230311200554018

思路分析

解法一:模拟行遍历(推荐)

核心思路

  • 维护 numRowsStringBuilder(或字符串),每个对应 Z 形中的一行。
  • 用一个变量 curRow 记录当前字符应追加到哪一行,用布尔变量 goingDown 记录方向。
  • 遍历字符串时:将当前字符追加到 rows[curRow];当 curRow == 0 时向下走,当 curRow == numRows - 1 时向上走,即在首尾行翻转方向。
  • 最终按顺序将所有行拼接得到结果。
  • 特判 numRows == 1 时直接返回原串,避免死循环。


复杂度分析

  • 时间复杂度:O(n),其中 n 表示字符串长度,每个字符恰好被访问一次。
  • 空间复杂度:O(n),其中 n 表示字符串长度,所有行缓冲区合计存储 n 个字符。
class Solution {
    public String convert(String s, int numRows) {
        // 只有一行时无需变换
        if (numRows == 1) {
            return s;
        }

        StringBuilder[] rows = new StringBuilder[numRows];
        for (int i = 0; i < numRows; i++) {
            rows[i] = new StringBuilder();
        }

        int curRow = 0;
        boolean goingDown = false;

        for (char c : s.toCharArray()) {
            rows[curRow].append(c);
            // 在首行或末行时翻转方向
            if (curRow == 0 || curRow == numRows - 1) {
                goingDown = !goingDown;
            }
            curRow += goingDown ? 1 : -1;
        }

        StringBuilder result = new StringBuilder();
        // 按行顺序拼接结果
        for (StringBuilder row : rows) {
            result.append(row);
        }
        return result.toString();
    }
}
func convert(s string, numRows int) string {
    // 只有一行时无需变换
    if numRows == 1 {
        return s
    }

    rows := make([][]byte, numRows)
    curRow := 0
    goingDown := false

    for i := 0; i < len(s); i++ {
        rows[curRow] = append(rows[curRow], s[i])
        // 在首行或末行时翻转方向
        if curRow == 0 || curRow == numRows-1 {
            goingDown = !goingDown
        }
        if goingDown {
            curRow++
        } else {
            curRow--
        }
    }

    // 按行顺序拼接结果
    result := make([]byte, 0, len(s))
    for _, row := range rows {
        result = append(result, row...)
    }
    return string(result)
}

相似题目

题目 难度 考察点
443. 压缩字符串 中等 字符串 / 双指针模拟
38. 外观数列 中等 字符串 / 游程编码
48. 旋转图像 中等 数组 / 矩阵变换
54. 螺旋矩阵 中等 数组 / 矩阵模拟
59. 螺旋矩阵 II 中等 数组 / 矩阵模拟
165. 比较版本号 中等 字符串 / 分割解析
本文作者:
本文链接: https://hgnulb.github.io/blog/2025/43202799
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!