iT邦幫忙

1

解LeetCode的學習筆記Day6_Zigzag Conversion

LFI 2025-09-27 11:47:56128 瀏覽
  • 分享至 

  • xImage
  •  

今天是紀錄LeetCode解題的第六天

第六題題目:https://ithelp.ithome.com.tw/upload/images/20250927/20179234iWpF6MhN5S.png
給一個字串假設是"PAYPALISHIRING",把它以Z字形排列輸出成"PAHNAPLSIIGYIR"

解題思路

根據範例一的numRows=3,我們知道要存成三列,每當cur_row=0、1(在第一、二列時)我們要將下一個字元放在下一列,當cur_row=2(在第三列)時,要將下一個字元放回上一列,也就是說碰到0邊界就往下一列存放直到碰到numRows邊界就返回上一列存放

程式碼

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows == 1 or numRows >= len(s):
            return s
        result = [""] * numRows
        cur_row = 0
        going_down = False
        for c in s:
            result[cur_row] += c
            if cur_row == 0 or cur_row == numRows - 1:
                going_down = not going_down
            cur_row += 1 if isreverse else -1
        return "".join(result)

執行過程

初始狀態
s = "PAYPALISHIRING"
numRows = 3
rows = ['', '', ''] (每列是一個空字串)
cur_row = 0 (從第一行開始)
going_down = False

第一次執行

  • 第 1 個字元 'P'
  • 放入 rows[0] → rows = ['P', '', '']
  • 因為 cur_row == 0,反轉方向 → going_down = True
  • 移動到下一行 → cur_row = 1

第二次執行

  • 第 2 個字元 'A'
  • 放入 rows[1] → rows = ['P', 'A', '']
  • 移動到下一行 → cur_row = 2

第三次執行

  • 第 3 個字元 'Y'
  • 放入 rows[2] → rows = ['P', 'A', 'Y']
  • 因為 cur_row == numRows-1,反轉方向 → going_down = False
  • 移動到上一行 → cur_row = 1

第四次執行

  • 第 4 個字元 'P'
  • 放入 rows[1] → rows = ['P', 'AP', 'Y']
  • 移動到上一行 → cur_row = 0

依此類推最後會得到rows = ['PAHN','APLSIIG','YIR'],接著合併回傳就是答案了


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言