LeetCode 1440: Evaluate Boolean Expression
LeetCode 1440 Solution Explanation
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.
: :
LeetCode 1440 Solutions in Java, C++, Python
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'};
}
}
Interactive Code Editor for LeetCode 1440
Improve Your LeetCode 1440 Solution
Use the editor below to refine the provided solution for LeetCode 1440. Select a programming language and try the following:
- Add import statements 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.
Loading editor...