Approach
Depth-first search
For Parsing A Boolean Expression, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 46 lines of Java from the credited upstream file 1106.java.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public boolean parseBoolExpr(String expression) {3 return dfs(expression, 0, expression.length() - 1);4 }5 6 private boolean dfs(final String expression, int s, int e) {7 if (s == e)8 return expression.charAt(s) == 't';9 10 List<Boolean> exps = new ArrayList<>();11 int layer = 0;12 int left = 0;13 char op = ' ';14 15 for (int i = s; i <= e; ++i) {16 char c = expression.charAt(i);17 if (layer == 0 && (c == '!' || c == '&' || c == '|'))18 op = c;19 else if (c == '(' && ++layer == 1)20 left = i + 1;21 else if (c == ')' && --layer == 0)22 exps.add(dfs(expression, left, i - 1));23 else if (c == ',' && layer == 1) {24 exps.add(dfs(expression, left, i - 1));25 left = i + 1;26 }27 }28 29 if (op == '&') {30 boolean ans = true;31 for (boolean exp : exps)32 ans &= exp;33 return ans;34 }35 36 if (op == '|') {37 boolean ans = false;38 for (boolean exp : exps)39 ans |= exp;40 return ans;41 }42 43 return !exps.get(0);44 }45}46