-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution224.java
More file actions
executable file
·58 lines (56 loc) · 2.11 KB
/
Copy pathSolution224.java
File metadata and controls
executable file
·58 lines (56 loc) · 2.11 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
import java.util.*;
class Solution224 {
public int calculate(String s) {
Deque<String>stack = new ArrayDeque<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ')') { // 弹栈,直到遇到左括号
StringBuilder sb = new StringBuilder();
while(!stack.peekLast().equals("("))
sb.insert(0, stack.removeLast());
stack.removeLast(); // 弹出对应的左括号
stack.addLast(cal(sb.toString()));
}
else if (s.charAt(i) != ' ') stack.addLast(s.substring(i, i + 1));
}
if (!stack.isEmpty()) {
StringBuffer sb = new StringBuffer();
while(!stack.isEmpty())
sb.insert(0, stack.removeLast());
stack.addLast(cal(sb.toString()));
}
String res = stack.peekLast();
return Integer.valueOf(res);
}
public String cal(String str) {
int res = 0;
int end = str.length() - 1; // 记录每个数字
for (int i = end; i >= 0 ; i--) {
if (str.charAt(i) == '+') {
int temp = Integer.valueOf(str.substring(i + 1, end + 1));
end = i - 1;
res += temp;
}
else if (str.charAt(i) == '-') {
if (i > 0 && str.charAt(i - 1) == '+') {
int temp = Integer.valueOf(str.substring(i + 1, end + 1));
i--;
end = i - 1;
res -= temp;
}
else if (i > 0 && str.charAt(i - 1) == '-') {
int temp = Integer.valueOf(str.substring(i + 1, end + 1));
i--;
end = i - 1;
res += temp;
}
else {
int temp = Integer.valueOf(str.substring(i + 1, end + 1));
end = i - 1;
res -= temp;
}
}
}
if (str.charAt(0) != '-') res += Integer.valueOf(str.substring(0, end + 1));
return String.valueOf(res);
}
}