给你一个以字符串形式表述的 布尔表达式(boolean) expression,返回该式的运算结果。
有效的表达式需遵循以下约定:
栈模拟过程
class Solution:
def parseBoolExpr(self, expression: str) -> bool:
stack = []
left = -1
for index, ex in enumerate(expression):
if ex == ",":
continue
if ex == ")":
print(stack)
dic_count = {"f":0,"t":0}
while stack[-1] != "(":
if stack[-1] == "(":
break
dic_count[stack[-1]] += 1
stack.pop()
stack.pop() # 删除左括号
if stack[-1] == "!":
if dic_count["f"]:
stack.pop()
stack.append("t")
if dic_count["t"]:
stack.pop()
stack.append("f")
if stack[-1] == "|":
if dic_count["t"]:
stack.pop()
stack.append("t")
else:
stack.pop()
stack.append("f")
if stack[-1] == "&":
if dic_count["f"]:
stack.pop()
stack.append("f")
else:
stack.pop()
stack.append("t")
if ex != ")":
stack.append(ex)
if stack[0] == "f":
return False
else:
return True