-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_772.java
More file actions
53 lines (49 loc) · 1.64 KB
/
Copy pathP_772.java
File metadata and controls
53 lines (49 loc) · 1.64 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
package leetcode.hard;
import java.util.Deque;
import java.util.LinkedList;
public class P_772 {
public int calculate(String s) {
int l1 = 0, o1 = 1;
int l2 = 1, o2 = 1;
final Deque<Integer> stack = new LinkedList<>();
for (int i = 0; i < s.length(); i++) {
final char c = s.charAt(i);
if (Character.isDigit(c)) {
int num = c - '0';
while (++i < s.length() && Character.isDigit(s.charAt(i))) {
num = num * 10 + (s.charAt(i) - '0');
}
l2 = o2 == 1 ? l2 * num : l2 / num;
i--;
} else if (c == '(') {
stack.addFirst(l1);
stack.addFirst(o1);
stack.addFirst(l2);
stack.addFirst(o2);
l1 = 0;
o1 = 1;
l2 = 1;
o2 = 1;
} else if (c == ')') {
final int num = l1 + o1 * l2;
o2 = stack.removeFirst();
l2 = stack.removeFirst();
o1 = stack.removeFirst();
l1 = stack.removeFirst();
l2 = o2 == 1 ? l2 * num : l2 / num;
} else if (c == '*' || c == '/') {
o2 = c == '*' ? 1 : -1;
} else if (c == '+' || c == '-') {
if (c == '-' && (i == 0 || s.charAt(i - 1) == '(')) {
o1 = -1;
continue;
}
l1 += o1 * l2;
o1 = c == '+' ? 1 : -1;
l2 = 1;
o2 = 1;
}
}
return l1 + o1 * l2;
}
}