首页 > 代码库 > Leetcode: Evaluate Reverse Polish Notation

Leetcode: 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  

分析:Reverse Polish Notation可以通过post traversal计算树来得到,我们可以通过栈来evaluate它的值,代码如下:
 1 class Solution { 2 public: 3     int evalRPN(vector<string> &tokens) { 4         int result = 0; 5         stack<int> S; 6          7         for(int i = 0; i < tokens.size(); i++){ 8             if(is_operator(tokens[i])){ 9                 int rv = S.top();10                 S.pop();11                 int lv = S.top();12                 S.pop();13                 if(tokens[i] == "+")14                     S.push(lv + rv);15                 else if(tokens[i] == "-")16                     S.push(lv - rv);17                 else if(tokens[i] == "*")18                     S.push(lv * rv);19                 else if(tokens[i] == "/")20                     S.push(lv / rv);21             }else{22                 S.push(atoi(tokens[i].c_str()));23             }24         }25         return S.top();26     }27     28     bool is_operator(string s){29         return s == "+" || s == "-" || s == "*" || s == "/";30     }31 };

 

Leetcode: Evaluate Reverse Polish Notation