Leetcode 1106. Parsing A Boolean Expression

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Parsing A Boolean Expression

2. Solution

解析:Version 1,使用栈来求解,当碰到逻辑运算、(以及操作数时,入栈,当每次碰到)时,先将操作数出栈,然后再将逻辑运算出栈,计算逻辑运算的结果,将结果压入栈中,最终,栈中只剩下最终结果。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
def parseBoolExpr(self, expression: str) -> bool:
operations = []
for i in range(len(expression)):
if expression[i] == '&' or expression[i] == '|' or expression[i] == '!' or expression[i] == '(':
operations.append(expression[i])
elif expression[i] == 't':
operations.append(True)
elif expression[i] == 'f':
operations.append(False)
elif expression[i] == ')':
operators = []
while operations[-1] != '(':
operators.append(operations.pop(-1))
operations.pop(-1)
logic = operations.pop(-1)
if logic == '&':
temp = True
for val in operators:
temp &= val
elif logic == '|':
temp = False
for val in operators:
temp |= val
else:
temp = not operators[-1]
operations.append(temp)

return operations[-1]

Reference

  1. https://leetcode.com/problems/parsing-a-boolean-expression/
如果有收获,可以请我喝杯咖啡!