精華區beta Marginalman 關於我們 聯絡資訊
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
sustainer123: 大師 10/20 09:31