Problem
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
.'&(subExpr1, subExpr2, ..., subExprn)'
that evaluates to the logical AND of the inner expressionssubExpr1, subExpr2, ..., subExprn
wheren >= 1
.'|(subExpr1, subExpr2, ..., subExprn)'
that evaluates to the logical OR of the inner expressionssubExpr1, subExpr2, ..., subExprn
wheren >= 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.
Examples
Solution
Method 1 - Using Stack
We can evaluate the Boolean expression using a stack-based approach. Here is a step-by-step description:
- Stack Usage: Use a stack to keep track of characters and sub-expressions as we parse through the input string.
- Character Handling:
- Operands: Push
t
andf
onto the stack. - Operators and Parentheses: When encountering
&
,|
, and!
, push them onto the stack. - Closing Parenthesis
)
: Start evaluating the expression when encountering)
. Pop elements from the stack until a matching(
is found. Depending on the operator, compute the result for the sub-expression and push the result back onto the stack.
- Operands: Push
- Evaluation of Sub-Expressions:
- NOT
!
: Negate the sub-expression. - AND
&
: Evaluate the AND operation over multiple sub-expressions. - OR
|
: Evaluate the OR operation over multiple sub-expressions.
- NOT
- Final Result: The final result of the evaluation will be left at the top of the stack once the entire expression is processed.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the length of the string expression. This accounts for traversing and processing each character in the expression. - 🧺 Space complexity:
O(n)
in the worst case, due to the stack usage for storing the characters and intermediate results.