首页 > 其他 > 详细

LeetCode - Evaluate Reverse Polish Notation

时间:2014-02-26 16:48:37      阅读:275      评论:0      收藏:0      [点我收藏+]

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:

bubuko.com,布布扣
 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 };
bubuko.com,布布扣

LeetCode - Evaluate Reverse Polish Notation

原文:http://www.cnblogs.com/zhuli19901106/p/3568133.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!