File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed
solution/0224.Basic Calculator Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments