置頂

我的 VPython 教學文件 (HackMD 版本)

VPython 教學文件目錄 安裝及測試 基本語法 等速度直線運動 自由落下 終端速度 水平抛射 使用For迴圈計算水平抛射資料 斜向抛射 圓周運動 簡諧運動 單擺 木塊彈簧系統分離 重力及簡諧 行星運動 相疊木塊 雙重簡諧運動 一維彈性碰撞 ...

熱門文章

2026年10月8日 星期四

LeetCode 解題筆記:1021. Remove Outermost Parentheses

作者:王一哲
日期:2026年10月8日


LeetCode 題目連結:1021. Remove Outermost Parentheses

解題想法


簡單題。題目給一個字串 $s$,$s$ 之中只有 $(, )$,保證是合法的括號字串,回傳移除最外層的括號之後的字串。用一個變數 $balance$ 記錄左括號減去右括號的數量,字串 $t$ 儲存答案。用一個 for 迴圈依序讀取 $s$ 的字元 $c$,如果 $c$ 是 $($,先將 $balance$ 加 1,如果此時 $balance > 1$,代表有最外層的括號,$c$ 加入 $t$;如果 $c$ 是 $)$,先將 $balance$ 減 1,如果此時 $balance > 0$,代表有最外層的括號,$c$ 加入 $t$。

Python 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 19.42 MB, beats 8.63%.
class Solution:
    def removeOuterParentheses(self, s: str) -> str:
        balance = 0  # 左括號數量 - 右括號數量
        t = ""  # 答案
        for c in s:
            if c == '(':  # (
                balance += 1
                if balance > 1: t += c  # 有最外層 (
            else:  # (
                balance -= 1
                if balance > 0: t += c  # 有最外層 (
        
        return t


C++ 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 9.04 MB, beats 21.38%.
class Solution {
public:
    string removeOuterParentheses(string s) {
        int balance = 0;  // 左括號數量 - 右括號數量
        string t;  // 答案
        for(char c : s) {
            if (c == '(') {  // (
                balance++;
                if (balance > 1) t += c;  // 有最外層 (
            } else {  // (
                balance--;
                if (balance > 0) t += c;  // 有最外層 (
            }
        }
        return t;
    }
};


沒有留言:

張貼留言