Re: [閒聊] 每日leetcode

作者: dont   2024-10-20 09:29:09
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'
```
作者: sustainer123 (caster)   2024-10-20 09:31:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com