Re: [閒聊] 每日leetcode

看板Marginalman作者 (dont)時間1年前 (2024/10/20 09:29), 編輯推噓0(001)
留言1則, 1人參與, 1年前最新討論串1012/1554 (看更多)
1106. Parsing A Boolean Expression ## 思路 掃字串存Stack 1. 如果ch是')' 就pop stack直到'(' 並記錄目前的true/false 然後根據operator (!, &, |)運算把結果丟回Stack 2. 如果ch是','跳過, 其餘丟Stack ## Code ```python class Solution: def parseBoolExpr(self, expression: str) -> bool: stack = [] for ch in expression: if ch == ')': has_true = has_false = False while stack[-1] != '(': prev = stack.pop() if prev == 't': has_true = True else: has_false = True stack.pop() # ( op = stack.pop() # & | ! if op == '!': res = not has_true elif op == '&': res = not has_false else: res = has_true stack.append('t' if res else 'f') elif ch != ',': stack.append(ch) return stack[-1] == 't' ``` -- https://i.imgur.com/kyBhy6o.jpeg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 185.213.82.84 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1729387752.A.20C.html

10/20 09:31, 1年前 , 1F
大師
10/20 09:31, 1F
文章代碼(AID): #1d55pe8C (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1d55pe8C (Marginalman)