Skip to content

Commit 83ef740

Browse files
authored
Create Solution.java
1 parent 229d721 commit 83ef740

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public int calculate(String s) {
3+
char[] cs = s.toCharArray();
4+
Deque<Character> op = new ArrayDeque<>();
5+
Deque<Integer> num = new ArrayDeque<>();
6+
for (int i = 0; i < cs.length; ++i) {
7+
if (cs[i] == '(' || cs[i] == '+' || cs[i] == '-') {
8+
op.push(cs[i]);
9+
} else if (cs[i] == ')') {
10+
op.pop();
11+
if (!op.isEmpty() && op.peek() != '(') {
12+
calc(op, num);
13+
}
14+
} else if (Character.isDigit(cs[i])) {
15+
int j = i;
16+
int k = 0;
17+
while (j < cs.length && Character.isDigit(cs[j])) {
18+
k = k * 10 + cs[j] - '0';
19+
++j;
20+
}
21+
num.push(k);
22+
i = j - 1;
23+
if (!op.isEmpty() && op.peek() != '(') {
24+
calc(op, num);
25+
}
26+
}
27+
}
28+
return num.peek();
29+
}
30+
31+
private void calc(Deque<Character> op, Deque<Integer> num) {
32+
int y = num.pop();
33+
int x = num.pop();
34+
if (op.pop() == '+') {
35+
num.push(x + y);
36+
} else {
37+
num.push(x - y);
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)