File tree 2 files changed +68
-0
lines changed
Evaluate Reverse Polish Notation
2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 典型的利用堆栈的题目
2
+ // Runtime: 16 ms, faster than 100.00% of C++ online submissions for Evaluate Reverse Polish Notation.
3
+ // Memory Usage: 11.5 MB, less than 39.61% of C++ online submissions for Evaluate Reverse Polish Notation.
4
+ class Solution
5
+ {
6
+ public:
7
+ int evalRPN (vector<string>& tokens)
8
+ {
9
+ stack<int > memo;
10
+ int res;
11
+
12
+ for (auto token : tokens)
13
+ {
14
+ char chr = token[0 ];
15
+
16
+ // 如果是数字的话就压入堆栈
17
+ if (chr >= ' 0' && chr <= ' 9' || token.size () > 1 )
18
+ memo.push (atoi (token.c_str ()));
19
+
20
+ // 如果是运算符的话就要从堆栈中提取出两个运算数进行运算
21
+ else
22
+ {
23
+ int op1 = memo.top ();
24
+ memo.pop ();
25
+ int op2 = memo.top ();
26
+ memo.pop ();
27
+
28
+ if (chr == ' +' )
29
+ res = op2 + op1;
30
+ else if (chr == ' -' )
31
+ res = op2 - op1;
32
+ else if (chr == ' *' )
33
+ res = op2 * op1;
34
+ else if (chr == ' /' )
35
+ res = op2 / op1;
36
+
37
+ memo.push (res);
38
+ }
39
+ }
40
+ return memo.top ();
41
+ }
42
+ };
Original file line number Diff line number Diff line change
1
+ # 这里要注意python中的 // 运算符的问题所在
2
+
3
+ # Runtime: 36 ms, faster than 100.00% of Python3 online submissions for Evaluate Reverse Polish Notation.
4
+ # Memory Usage: 12.9 MB, less than 24.06% of Python3 online submissions for Evaluate Reverse Polish Notation.
5
+
6
+ class Solution :
7
+ def evalRPN (self , tokens : 'List[str]' ) -> 'int' :
8
+ memo = []
9
+
10
+ for token in tokens :
11
+ if '0' <= token <= '9' or len (token ) > 1 :
12
+ memo .append (int (token ))
13
+ else :
14
+ op1 = memo .pop ()
15
+ op2 = memo .pop ()
16
+
17
+ if token == '+' :
18
+ memo .append (op2 + op1 )
19
+ elif token == '-' :
20
+ memo .append (op2 - op1 )
21
+ elif token == '*' :
22
+ memo .append (op2 * op1 )
23
+ else :
24
+ memo .append (int (op2 / op1 ))
25
+
26
+ return memo .pop ();
You can’t perform that action at this time.
0 commit comments