Leetcode 1106. Parsing A Boolean Expression
Posted SnailTyan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1106. Parsing A Boolean Expression相关的知识,希望对你有一定的参考价值。
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
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 = 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
以上是关于Leetcode 1106. Parsing A Boolean Expression的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 1106 解析布尔表达式[栈] HERODING的LeetCode之路
glibc: Parsing a Template String 如何解析printf格式化
Expected a key while parsing a block mapping.
Error parsing XML: not well-formed (invalid token) 报错+R文件消失解决的方法