跳过正文
  1. leetcode 题解/

6_Z_字形变换

·108 字·1 分钟

类型:字符串

    1. Z 字形变换 💛

    https://leetcode-cn.com/problems/zigzag-conversion/

    ❓ 对于字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

    比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

    P   A   H   N
    A P L S I I G
    Y   I   R

    输出:”PAHNAPLSIIGYIR“

    💡 Z 形逐行添加

    初始化 n 行字符串,Z 形访问并添加字符到各行的字符串中,移动到最顶行或最底行时转换方向。最后将各行合并。

    class Solution:
        def convert(self, s: str, numRows: int) -> str:
            if not s or numRows <= 1:
                return s
    
            rows = ["" for _ in range(numRows)]
            direction = -1
            r = 0
            for i in range(len(s)):
                rows[r] += s[i]
                if r == 0 or r == numRows - 1:
                    direction *= -1
                r += direction
            ans = ""
            for row in rows:
                ans += row
            return ans

    时间复杂度:O(n),空间复杂度:O(n)