150. Evaluate Reverse Polish Notation

Posted 为了更优秀的你,加油!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
    }
};

 

以上是关于150. Evaluate Reverse Polish Notation的主要内容,如果未能解决你的问题,请参考以下文章

150. Evaluate Reverse Polish Notation

150. Evaluate Reverse Polish Notation

leetcode150 Evaluate Reverse Polish Notation

[leetcode-150-Evaluate Reverse Polish Notation]

刷题-LeetCode150 Evaluate Reverse Polish Notation

[LeetCode] 150. Evaluate Reverse Polish Notation