-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC1106.java
More file actions
73 lines (64 loc) · 1.91 KB
/
LC1106.java
File metadata and controls
73 lines (64 loc) · 1.91 KB
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
66
67
68
69
70
71
72
73
/*
* LC1106
*/
import java.util.*;
public class LC1106 {
public static char evaluate(ArrayList<Character> list, char op) {
if (op == '&') { // and operator
if (find(list, 'f')) {
return 'f';
} else {
return 't';
}
} else if (op == '|') { // or operator
if (find(list, 't')) {
return 't';
} else {
return 'f';
}
} else if (op == '!') { // not operator
return (list.get(0) == 't' ? 'f' : 't');
} else {
return 'f'; // default case, should not occur
}
}
public static boolean find(ArrayList<Character> list, char val) {
for (char ch : list) {
if (ch == val) {
return true;
}
}
return false;
}
public static boolean parseBoolExpr(String expression) {
Stack<Character> stack = new Stack<>();
int n = expression.length();
for (int i = 0; i < n; i++) {
char ch = expression.charAt(i);
if (ch == ')') {
ArrayList<Character> list = new ArrayList<>();
while (stack.peek() != '(') {
list.add(stack.pop());
}
stack.pop(); // remove '('
char op = stack.pop();
char ans = evaluate(list, op);
stack.push(ans);
} else {
if (ch != ',') {
stack.push(ch);
}
}
}
return stack.peek() == 't';
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter The String Here : ");
String str = sc.nextLine();
System.out.println();
Boolean ans = parseBoolExpr(str);
System.out.println(ans);
sc.close();
}
}