-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution1106.java
65 lines (58 loc) · 2.01 KB
/
Solution1106.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package leetcode.stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Solution1106 {
public static void main(String[] args) {
System.out.println(new Solution1106().parseBoolExpr("!(&(f,t))"));
}
public boolean parseBoolExpr(String expression) {
Stack<Character> operators = new Stack<>();
Stack<Character> elements = new Stack<>();
char[] charArray = expression.toCharArray();
for (char c : charArray) {
if (c == '&' || c == '|' || c == '!') {
operators.push(c);
// 空格来分隔需要判断的元素
elements.push(' ');
} else if (c == '(' || c == ',') {
continue;
} else if (c == ')') {
Character operator = operators.pop();
ArrayList<Character> temp = new ArrayList<>();
while (elements.peek() != ' ') {
temp.add(elements.pop());
}
// 占位符不要了
elements.pop();
if (operator == '&') {
if (temp.contains('f')) {
elements.push('f');
} else {
elements.push('t');
}
continue;
}
if (operator == '|') {
if (temp.contains('t')) {
elements.push('t');
} else {
elements.push('f');
}
continue;
}
if (operator == '!') {
Character character = temp.get(0);
if (character == 't') {
elements.push('f');
} else {
elements.push('t');
}
}
} else {
elements.add(c);
}
}
return elements.get(0) == 't';
}
}