当前位置: 代码迷 >> 综合 >> Leetcode 1106. Parsing A Boolean Expression
  详细解决方案

Leetcode 1106. Parsing A Boolean Expression

热度:83   发布时间:2023-12-12 21:03:03.0

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

1. Description

Parsing A Boolean Expression

2. Solution

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

  • 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 = Truefor val in operators:temp &= valelif logic == '|':temp = False for val in operators:temp |= valelse:temp = not operators[-1]operations.append(temp)return operations[-1]

Reference

  1. https://leetcode.com/problems/parsing-a-boolean-expression/
  相关解决方案