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