LeetCode 1440: Evaluate Boolean Expression Solution
Master LeetCode problem 1440 (Evaluate Boolean Expression), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1440. Evaluate Boolean Expression
Problem 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.
: :
Solution Code
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'};
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1440 (Evaluate Boolean Expression)?
This page provides optimized solutions for LeetCode problem 1440 (Evaluate Boolean Expression) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1440 (Evaluate Boolean Expression)?
The time complexity for LeetCode 1440 (Evaluate Boolean Expression) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1440 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1440 in Java, C++, or Python.