File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int calculate (String s ) {
3
+ if (s .isEmpty ()) {
4
+ return 0 ;
5
+ }
6
+
7
+ int result = 0 , sign = 1 ;
8
+
9
+ Stack <Integer > st = new Stack <>();
10
+
11
+ for (int i = 0 ; i < s .length (); i ++) {
12
+ char c = s .charAt (i );
13
+
14
+ if (c == ' ' ) {
15
+ continue ;
16
+ }
17
+
18
+ if (Character .isDigit (c )) {
19
+ int sum = c - '0' ;
20
+
21
+ while (i + 1 < s .length () && Character .isDigit (s .charAt (i + 1 ))) {
22
+ sum = sum * 10 + s .charAt (i + 1 ) - '0' ;
23
+ ++i ;
24
+ }
25
+
26
+ result = result + sum * sign ;
27
+ } else if (c == '+' ) {
28
+ sign = 1 ;
29
+ } else if (c == '-' ) {
30
+ sign = -1 ;
31
+ } else if (c == '(' ) {
32
+ st .push (result );
33
+ st .push (sign );
34
+
35
+ result = 0 ;
36
+ sign = 1 ;
37
+ } else if (c == ')' ) {
38
+ int prevSign = st .pop ();
39
+ int prevResult = st .pop ();
40
+
41
+ result = result * prevSign + prevResult ;
42
+ }
43
+ }
44
+
45
+ return result ;
46
+ }
47
+ }
You can’t perform that action at this time.
0 commit comments