给你一个以字符串形式表述的 布尔表达式(boolean) expression
,返回该式的运算结果。
有效的表达式需遵循以下约定:
"t"
,运算结果为True
"f"
,运算结果为False
"!(expr)"
,运算过程为对内部表达式expr
进行逻辑 非的运算(NOT)"&(expr1,expr2,...)"
,运算过程为对 2 个或以上内部表达式expr1, expr2, ...
进行逻辑 与的运算(AND)"|(expr1,expr2,...)"
,运算过程为对 2 个或以上内部表达式expr1, expr2, ...
进行逻辑 或的运算(OR)
示例 1:
输入:expression = "!(f)" 输出:true
示例 2:
输入:expression = "|(f,t)" 输出:true
示例 3:
输入:expression = "&(t,f)" 输出:false
示例 4:
输入:expression = "|(&(t,f,t),!(t))" 输出:false
思路:双栈,一个存运算数,一个存运算符
代码
class Solution: def parseBoolExpr(self, expression: str) -> bool: stack1 = [] stack2 = [] def calc(a, b, c) -> bool: a = True if a == 't' else False b = True if b == 't' else False if c == '&': return a and b else: return a or b for i in expression: if i == ',': continue elif i == '(': stack1.append('(') elif i == '&' or i == '|' or i == '!': stack2.append(i) elif i == ')': result = stack1.pop() if stack2[-1] == '!': stack1.pop() stack2.pop() result = 't' if result == 'f' else 'f' stack1.append(result) continue while stack1[-1] != "(": result = 't' if calc(result, stack1.pop(), stack2[-1]) is True else 'f' stack1.pop() stack2.pop() stack1.append(result) else: stack1.append(i) return True if stack1[0] == 't' else False expression = "|(&(t,f,t),!(t))" s = Solution() print(s.parseBoolExpr(expression))
结果