日期: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;
}
};
沒有留言:
張貼留言