Minimum Cost to Change the Final Value of Expression LeetCode solution in Java

1
class Solution {
2
Deque<int[]> stack = new ArrayDeque<>();
3
Deque<Character> opStack = new ArrayDeque<>();
4

5
public int minOperationsToFlip(String expression) {
6
for (char ch : expression.toCharArray()) {
7
if (ch == '(') {
8
opStack.push(ch);
9
} else if (ch == ')') {
10
while (opStack.peek() != '(') {
11
go();
12
}
13
opStack.pop(); // remove '('
14
} else if (ch == '&' || ch == '|') {
15
while (!opStack.isEmpty() && opStack.peek() != '(') {
16
go();
17
}
18
opStack.push(ch);
19
} else { // num
20
stack.push(new int[] {ch, 1});
21
}
22
}
23
while (!opStack.isEmpty()) {
24
go();
25
}
26

27
return stack.peek()[1];
28
}
29

30
private void go() {
31
stack.push(check(opStack.pop(), stack.pop(), stack.pop()));
32
}
33

34
private int[] check(char op, int[] r, int[] l) {
35
int[] ans;
36
int rval = r[0], rcost = r[1];
37
int lval = l[0], lcost = l[1];
38
if (op == '|' && rval == '0' && lval == '0') {
39
ans = new int[] {'0', Math.min(rcost, lcost)};
40
} else if (op == '|' && rval == '1' && lval == '0') {
41
ans = new int[] {'1', 1};
42
} else if (op == '|' && rval == '0' && lval == '1') {
43
ans = new int[] {'1', 1};
44
} else if (op == '|' && rval == '1' && lval == '1') {
45
ans = new int[] {'1', 1 + Math.min(rcost, lcost)};
46
} else if (op == '&' && rval == '0' && lval == '0') {
47
ans = new int[] {'0', 1 + Math.min(rcost, lcost)};
48
} else if (op == '&' && rval == '1' && lval == '0') {
49
ans = new int[] {'0', 1};
50
} else if (op == '&' && rval == '0' && lval == '1') {
51
ans = new int[] {'0', 1};
52
} else { // &, 1, 1
53
ans = new int[] {'1', Math.min(rcost, lcost)};
54
}
55
return ans;
56
}
57
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0