Evaluate Reverse Polish Notation

2014.2.25 23:42

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

Solution:

  The Reverse Polish Notation is a postorder traversal of the syntax tree, which is constructed with operands and operators.

  With a stack it would be easy to process the sequence and calculate the result.

  Total time and space complexities are both O(n).

Accepted code:

 1 // 1AC, simple training on stack operation.
 2 #include <stack>
 3 #include <vector>
 4 using namespace std;
 5 
 6 class Solution {
 7 public:
 8     int evalRPN(vector<string> &tokens) {
 9         int i, n;
10         int op1, op2;
11         stack<int> nums;
12         bool is_op;
13         
14         n = (int)tokens.size();
15         for (i = 0; i < n; ++i) {
16             is_op = false;
17             if (tokens[i].length() == 1) {
18                 switch(tokens[i][0]) {
19                 case '+':
20                 case '-':
21                 case '*':
22                 case '/':
23                     is_op = true;
24                     break;
25                 }
26             }
27             
28             if (is_op) {
29                 if (nums.size() < 2) {
30                     // not enough operands
31                     return 0;
32                 }
33                 op2 = nums.top();
34                 nums.pop();
35                 op1 = nums.top();
36                 nums.pop();
37                 switch (tokens[i][0]) {
38                 case '+':
39                     nums.push(op1 + op2);
40                     break;
41                 case '-':
42                     nums.push(op1 - op2);
43                     break;
44                 case '*':
45                     nums.push(op1 * op2);
46                     break;
47                 case '/':
48                     if (op2 == 0) {
49                         // divide by 0
50                         return 0;
51                     }
52                     nums.push(op1 / op2);
53                     break;
54                 }
55             } else {
56                 if (sscanf(tokens[i].c_str(), "%d", &op1) != 1) {
57                     // invalid integer format
58                     return 0;
59                 }
60                 nums.push(op1);
61             }
62         }
63         int result = nums.top();
64         nums.pop();
65         
66         return result;
67     }
68 };

 

 posted on 2014-02-25 23:53  zhuli19901106  阅读(188)  评论(0编辑  收藏  举报