码迷,mamicode.com
首页 > 其他好文 > 详细

150. Evaluate Reverse Polish Notation

时间:2017-10-06 15:27:05      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:color   i++   dia   操作符   amp   cto   public   span   turn   

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();
    }
};

 

150. Evaluate Reverse Polish Notation

标签:color   i++   dia   操作符   amp   cto   public   span   turn   

原文地址:http://www.cnblogs.com/tsunami-lj/p/7631565.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!