-
Notifications
You must be signed in to change notification settings - Fork 13
/
solution.java
45 lines (40 loc) · 1.37 KB
/
solution.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.util.*;
class Solution {
public boolean parseBoolExpr(String expression) {
Stack<Character> stack = new Stack<>();
for (char c : expression.toCharArray()) {
if (c == ')') {
List<Character> subExpr = new ArrayList<>();
while (stack.peek() != '(') {
subExpr.add(stack.pop());
}
stack.pop(); // Remove '('
char op = stack.pop(); // Get the operator
if (op == '!') {
stack.push(subExpr.get(0) == 't' ? 'f' : 't');
} else if (op == '&') {
char result = 't';
for (char e : subExpr) {
if (e == 'f') {
result = 'f';
break;
}
}
stack.push(result);
} else if (op == '|') {
char result = 'f';
for (char e : subExpr) {
if (e == 't') {
result = 't';
break;
}
}
stack.push(result);
}
} else if (c != ',') {
stack.push(c);
}
}
return stack.peek() == 't';
}
}