Evaluate Reverse Polish Notation

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

分析:题目很简单,遇到操作符号,连续pop两个数字,计算后push进栈。最后返回栈的唯一一个数字。注意边界条件,如果vector的size为0,返回0。如果在进行数字处理的时候栈为空不能pop数字,返回0。 特别要注意的是,switch与剧中的条件需要能转化为整数,否则会报错。如果不懂的话,就用if吧。哈哈哈,我感觉自己很擅长栈呢(因为比较直观么 ==)。。21ms。

 1 class Solution {
 2 public:
 3     int evalRPN(vector<string>& tokens) {
 4         if(tokens.size() == 0) return 0;
 5         
 6         stack<int> result;
 7         int ope1 = 0, ope2 = 0;
 8         for(int i = 0; i < tokens.size(); i++){
 9             if(tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
10                 char temp = tokens[i][0];
11                 if(result.size() == 0) return 0;
12                 ope2 = result.top();
13                 result.pop();
14                 
15                 if(result.size() == 0) return 0;
16                 ope1 = result.top();
17                 result.pop();
18                 result.push(calculate(ope1, ope2, temp));
19             }
20             else result.push(s2int(tokens[i]));
21         }
22         return result.top();
23     }
24     int s2int(string s){
25         int negative = 0;
26         if(s[0] == '-') negative = 1;
27         
28         int result = 0;
29         int exponential = 1;
30         for(int i = s.length() - 1; i >= negative; i--){
31             int temp = s[i] - '0';
32             result += temp * exponential;
33             exponential *= 10;
34         }
35         if(negative) return -result;
36         return result;
37     }
38     int calculate(int ope1, int ope2, char opera){
39         switch(opera){
40             case '+': return ope1 + ope2;
41             case '-': return ope1 - ope2;
42             case '*': return ope1 * ope2;
43             case '/': return ope1 / ope2;
44         }
45     }
46 };
原文地址:https://www.cnblogs.com/amazingzoe/p/4444708.html