150. 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
解题思路:已知后缀表达式,求值。用一个栈就可以实现。划重点。string到int的转化函数 stoi.判断是数字还是操作符更好的做法:isdigit(tokens[i].back())
class Solution {
public:
    int calc(int &a, int &b, string op){
        if(op=="+")return a+b;
        else if(op=="-")return a-b;
        else if(op=="*")return a*b;
        else return a/b;
    }
    int evalRPN(vector<string>& tokens) {
        stack<int>nums;
        int top1,top2;
        for(int i=0;i<tokens.size();i++){
            if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/"){
                top2=nums.top();
                nums.pop();
                top1=nums.top();
                nums.pop();
                nums.push(calc(top1,top2,tokens[i]));
            }
            else{
                nums.push(stoi(tokens[i]));
            }
        }
        return nums.top();
    }
};

 

posted @ 2017-10-06 15:01  Tsunami_lj  阅读(131)  评论(0编辑  收藏  举报