Skip to content

Commit dc736c0

Browse files
committed
Time: 11 ms (65.99%), Space: 44.7 MB (20.91%) - LeetHub
1 parent 371bc0b commit dc736c0

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
}

0 commit comments

Comments
 (0)