-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSolution.java
56 lines (55 loc) · 1.88 KB
/
Solution.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
55
56
class Solution {
public int calculate(String s) {
s = s.replace(" ", "");
Stack<String> stack = new Stack<>();
int i = 0;
while (i < s.length()) {
if (s.charAt(i) == ')') {
Stack<String> cal = new Stack<>();
while (!stack.isEmpty() && !stack.peek().equals("(")) {
cal.push(stack.pop());
}
if (!stack.isEmpty() && stack.peek().equals("(")) stack.pop();
int temp = Integer.parseInt(cal.pop());
while (!cal.isEmpty()) {
String op = cal.pop();
if (op.equals("-")) {
temp -= Integer.parseInt(cal.pop());
} else {
temp += Integer.parseInt(cal.pop());
}
}
stack.push(temp + "");
} else if (s.charAt(i) == '(') {
stack.push("(");
} else if (s.charAt(i) == '+') {
stack.push("+");
} else if (s.charAt(i) == '-') {
stack.push("-");
} else {
int j = i;
while (j < s.length() && Character.isDigit(s.charAt(j))) {
j++;
}
stack.push(s.substring(i, j));
i = j - 1;
}
i++;
}
Stack<String> cal = new Stack<>();
while (!stack.isEmpty()) {
cal.push(stack.pop());
}
int temp = Integer.parseInt(cal.pop());
while (!cal.isEmpty()) {
String op = cal.pop();
if (op.equals("-")) {
temp -= Integer.parseInt(cal.pop());
} else {
temp += Integer.parseInt(cal.pop());
}
}
stack.push(temp + "");
return Integer.parseInt(stack.pop());
}
}