-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1106. Parsing A Boolean Expression
62 lines (59 loc) · 1.76 KB
/
1106. Parsing A Boolean Expression
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
class Solution {
public boolean parseBoolExpr(String expression) {
Stack<Character> stack=new Stack<>();
for(char c:expression.toCharArray()){
switch(c) {
case 't':
case 'f':
case '!':
case '&':
case '|':
stack.push(c);
break;
case '(':
case ',':
break;
case ')':
evaluvate(stack);
break;
}
}
while(stack.size()!=1){
evaluvate(stack);
}
return stack.peek()=='t'?true:false;
}
public void evaluvate( Stack<Character> stack){
List<Boolean> ans=new ArrayList<>();
char ch;
do{
ch=stack.pop();
switch(ch) {
case 't':
ans.add(Boolean.TRUE);
break;
case 'f' :
ans.add(Boolean.FALSE);
break;
case '|' :
boolean a=false;
for (Boolean b:ans){
a|=b;
}
stack.push(a==Boolean.TRUE?'t':'f');
break;
case '&' :
boolean c=true;
for (boolean b:ans){
c&=b;
}
stack.push(c==Boolean.TRUE?'t':'f');
break;
case '!' :
boolean d=ans.get(0);
stack.push(d==Boolean.TRUE?'f':'t');
break;
}
}while(ch!='!'&&ch!='|'&&ch!='&');
}
}