1440. Evaluate Boolean Expression
Explanation:
To evaluate a boolean expression, we can use a recursive approach where we evaluate subexpressions within parentheses first. We can then evaluate the result of each subexpression based on the operator present in the expression. The operands in the expression are either 't' or 'f' representing true or false.
- We iterate through the expression and recursively evaluate subexpressions within parentheses.
- For each subexpression, we evaluate it based on the operator present ('&', '|', or '!').
- If the operator is '&', we evaluate both subexpressions and return true only if both are true.
- If the operator is '|', we evaluate both subexpressions and return true if at least one is true.
- If the operator is '!', we return the negation of the evaluated subexpression.
- We continue evaluating the rest of the expression until we reach the end.
Time Complexity: O(n), where n is the length of the expression. Space Complexity: O(n) for the recursive stack.
: :
class Solution {
public boolean parseBoolExpr(String expression) {
return evaluate(expression, 0)[0];
}
private boolean[] evaluate(String exp, int start) {
char op = exp.charAt(start);
if (exp.charAt(start + 1) == '(') {
start += 2;
boolean[] res = new boolean[]{op == '!'};
while (exp.charAt(start) != ')') {
boolean[] val = evaluate(exp, start);
if (op == '&') res[0] &= val[0];
if (op == '|') res[0] |= val[0];
if (op == '!') res[0] = !val[0];
start += val.length + 1;
}
return res;
}
return new boolean[]{op == 't'};
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.