↓快轉到主要內容
  1. LeetCode/

LeetCode 1021: Remove Outermost Parentheses

·1 分鐘· ·
LeetCode Easy String Stack Bracket-Sequences
Wei Yi Chung
作者
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
目錄

基本資料
#

難易度: easy 第一次嘗試:2022-09-27

  • 提交紀錄:Wrong Answer → Accepted

解題思路
#

括號只有一種,stack 裡只會有 (,所以只需要記深度(Stack 模板一)。遇到 (:深度原本 > 0 才保留,再加一;遇到 ):先減一,減完還 > 0 才保留。這樣每個 primitive 最外面那一對就被去掉了。

我的嘗試
#

第一版用 stack 找出每一段 primitive,再用 temp[1:-1] 去掉頭尾,邏輯是對的但忘了 return;第二版補上就 AC 了。

正確解法
#

class Solution:
    def removeOuterParentheses(self, s: str) -> str:
        res, depth = [], 0
        for c in s:
            if c == "(":
                if depth > 0:
                    res.append(c)
                depth += 1
            else:
                depth -= 1
                if depth > 0:
                    res.append(c)
        return "".join(res)

複雜度
#

時間 O(n),空間 O(n)(輸出)。

要特別避免的錯誤
#

  • 左括號是加之前判斷,右括號是減之後判斷。

面試口說整理
#

括號只有一種,我用深度計數取代 stack:左括號在深度大於 0 時才保留,右括號減完之後深度還大於 0 才保留,這樣每一段最外層的括號就被去掉了。時間 O(n)。

相關文章

LeetCode 844: Backspace String Compare
·1 分鐘
LeetCode Easy Two-Pointers String Stack Simulation
LeetCode 844 解題筆記:用 stack 模擬退格;O(1) 空間的話從尾巴往前,遇到 # 就記下要跳過幾個字元
LeetCode 1002: Find Common Characters
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 1002 解題筆記:每個單字各自計數,對所有 Counter 取交集(每個字元取最小次數),再展開
LeetCode 929: Unique Email Addresses
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 929 解題筆記:用 @ 切開,只處理 local 的部分(+ 之後丟掉、去掉 .),接回 domain 後放進集合
LeetCode 944: Delete Columns to Make Sorted
·1 分鐘
LeetCode Easy Array String Longest-Increasing-Subsequence
LeetCode 944 解題筆記:用 zip(*strs) 取出每一欄,數有幾欄不是非遞減的
LeetCode 953: Verifying an Alien Dictionary
·1 分鐘
LeetCode Easy Array Hash-Table String
LeetCode 953 解題筆記:把字母對應到外星順序的 index,相鄰兩個單字找第一個不同的字元比較,沒有不同時短的要在前面
LeetCode 897: Increasing Order Search Tree
·1 分鐘
LeetCode Easy Stack Tree Depth-First-Search Binary-Search-Tree
LeetCode 897 解題筆記:中序遍歷,依序把節點接到一條只有右小孩的鏈上,左小孩設成 None;dummy 和移動的尾巴要分開