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