Parsing A Boolean Expression Problem
Description
LeetCode Problem 1106.
A boolean expression is an expression that evaluates to either true or false. It can be in one of the following shapes:
't'that evaluates totrue.'f'that evaluates tofalse.'!(subExpr)'that evaluates to the logical NOT of the inner expressionsubExpr.'&(subExpr_1, subExpr_2, ..., subExpr_n)'that evaluates to the logical AND of the inner expressionssubExpr_1, subExpr_2, ..., subExpr_nwheren >= 1.'|(subExpr_1, subExpr_2, ..., subExpr_n)'that evaluates to the logical OR of the inner expressionssubExpr_1, subExpr_2, ..., subExpr_nwheren >= 1.
Given a string expression that represents a boolean expression, return the evaluation of that expression.
It is guaranteed that the given expression is valid and follows the given rules.
Example 1:
Input: expression = "&(|(f))"
Output: false
Explanation:
First, evaluate |(f) --> f. The expression is now "&(f)".
Then, evaluate &(f) --> f. The expression is now "f".
Finally, return false.
Example 2:
Input: expression = "|(f,f,f,t)"
Output: true
Explanation: The evaluation of (false OR false OR false OR true) is true.
Example 3:
Input: expression = "!(&(f,t))"
Output: true
Explanation:
First, evaluate &(f,t) --> (false AND true) --> false --> f. The expression is now "!(f)".
Then, evaluate !(f) --> NOT false --> true. We return true.
Constraints:
1 <= expression.length <= 2 * 10^4- expression[i] is one following characters:
'(',')','&','|','!','t','f', and','.
Solution
Approach: One Stack
Every operator applies to the group in the parentheses right after it, and a group can be evaluated as soon as its ) shows up, because all its operands are already plain values by then. A stack is the natural way to do this, scanning left to right:
t,fand the operators!,&,|are pushed onto the stack.(and,are skipped: the operator is already on the stack, and the values separate themselves.- On
), pop values until the top of the stack is an operator, counting how manytandfwere popped. Then pop the operator and push the group's result:!: true if the single operand isf;&: true if there was nof;|: true if there was at least onet.
The result is again a single t or f, so the group's caller sees it just like any other operand. At the end, one value is left on the stack: the value of the whole expression.
The stack approach also avoids recursion. The expression can be up to 2 · 104 characters long, so a recursive parser could go thousands of levels deep on input like !(!(!(...))).
Complexity: O(n) time, since every character is pushed and popped at most once, and O(n) space for the stack.
class Solution:
def parseBoolExpr(self, expression: str) -> bool:
stack = []
for c in expression:
if c in "tf!&|":
stack.append(c)
elif c == ")":
# Pop the values of this group down to its operator.
trues = falses = 0
while stack[-1] in "tf":
if stack.pop() == "t":
trues += 1
else:
falses += 1
op = stack.pop()
if op == "!":
value = falses > 0 # one operand: true when it is f
elif op == "&":
value = falses == 0
else:
value = trues > 0
stack.append("t" if value else "f")
# "(" and "," carry no information: the operator is already on the stack.
return stack[-1] == "t"