File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int evalRPN (String [] tokens ) {
3
+ Stack <Integer > st = new Stack <>();
4
+
5
+ Set <String > operators = buildOperators ();
6
+
7
+ for (String token : tokens ) {
8
+ if (!operators .contains (token )) {
9
+ st .push (Integer .valueOf (token ));
10
+ continue ;
11
+ }
12
+
13
+ Integer num2 = st .pop ();
14
+ Integer num1 = st .pop ();
15
+
16
+ int tempResult = 0 ;
17
+
18
+ switch (token ) {
19
+ case "+" :
20
+ tempResult = num1 + num2 ;
21
+ break ;
22
+ case "-" :
23
+ tempResult = num1 - num2 ;
24
+ break ;
25
+ case "*" :
26
+ tempResult = num1 * num2 ;
27
+ break ;
28
+ case "/" :
29
+ tempResult = num1 / num2 ;
30
+ break ;
31
+ }
32
+
33
+ st .push (tempResult );
34
+ }
35
+
36
+ return st .pop ();
37
+ }
38
+
39
+ private Set <String > buildOperators () {
40
+ Set <String > operators = new HashSet <>();
41
+
42
+ operators .add ("+" );
43
+ operators .add ("-" );
44
+ operators .add ("*" );
45
+ operators .add ("/" );
46
+
47
+ return operators ;
48
+ }
49
+ }
You can’t perform that action at this time.
0 commit comments