-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParsingABoolenExp.java
54 lines (42 loc) · 1.63 KB
/
ParsingABoolenExp.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
import java.util.Stack;
public class ParsingABoolenExp {
public boolean parseBoolExpr(String expression) {
Stack<Character> exp = new Stack<>();
if (expression == null || expression.equals(""))
return false;
for (Character character : expression.toCharArray()) {
if (character == ')') {
Stack<Character> subExp = new Stack<>();
while (exp.peek() != '(') {
subExp.push(exp.pop());
}
exp.pop();
char oper = exp.pop();
if (oper == '!') {
char operand = subExp.pop();
exp.push(operand == 't' ? 'f' : 't');
} else if (oper == '&') {
boolean res = true;
while (!subExp.isEmpty()) {
res &= (subExp.pop() == 't');
}
exp.push(res ? 't' : 'f');
} else if (oper == '|') {
boolean res = false;
while (!subExp.isEmpty()) {
res |= (subExp.pop() == 't');
}
exp.push(res ? 't' : 'f');
}
} else if (character != ',') {
exp.push(character);
}
}
return exp.peek() == 't';
}
public static void main(String[] args) {
ParsingABoolenExp parsingABoolenExp = new ParsingABoolenExp();
System.out.println(parsingABoolenExp.parseBoolExpr("t,t,t")); // true
System.out.println(parsingABoolenExp.parseBoolExpr("t,t,f")); // false
}
}