File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
1106-parsing-a-boolean-expression Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public boolean parseBoolExpr (String expression ) {
3
+ Deque <Character > stk = new ArrayDeque <>();
4
+ for (int i = 0 ; i < expression .length (); ++i ) {
5
+ char c = expression .charAt (i );
6
+ if (c == ')' ) {
7
+ Set <Character > seen = new HashSet <>();
8
+ while (stk .peek () != '(' )
9
+ seen .add (stk .pop ());
10
+ stk .pop ();// pop out '('.
11
+ char operator = stk .pop (); // get operator for current expression.
12
+ if (operator == '&' ) {
13
+ stk .push (seen .contains ('f' ) ? 'f' : 't' ); // if there is any 'f', & expression results to 'f'
14
+ }else if (operator == '|' ) {
15
+ stk .push (seen .contains ('t' ) ? 't' : 'f' ); // if there is any 't', | expression results to 't'
16
+ }else { // ! expression.
17
+ stk .push (seen .contains ('t' ) ? 'f' : 't' ); // Logical NOT flips the expression.
18
+ }
19
+ }else if (c != ',' ) {
20
+ stk .push (c );
21
+ }
22
+ }
23
+ return stk .pop () == 't' ;
24
+ }
25
+ }
You can’t perform that action at this time.
0 commit comments