forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParsing A Boolean Expression.java
28 lines (27 loc) · 1.03 KB
/
Parsing A Boolean Expression.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public boolean parseBoolExpr(String expression) {
Deque<Boolean> stack = new ArrayDeque<>();
Deque<Character> op = new ArrayDeque<>();
Deque<Character> p = new ArrayDeque<>();
for (char ch : expression.toCharArray()){
switch(ch){
case '!', '&', '|' -> p.push(ch);
case 'f', 't' -> stack.push(ch == 't');
case '(' -> {op.push(ch); if (p.peek() == '!') op.push('!');}
case ')' -> {go(op, stack); op.pop(); p.pop();}
default -> {go(op, stack); op.push(p.peek());}
};
}
go(op, stack);
return stack.pop();
}
private void go(Deque<Character> op, Deque<Boolean> stack){
while(!op.isEmpty() && op.peek() != '('){
switch(op.pop()){
case '|' -> stack.push(stack.pop() | stack.pop());
case '&' -> stack.push(stack.pop() & stack.pop());
default -> stack.push(!stack.pop());
};
}
}
}