首页 > 其他分享 >150.evaluate-reverse-polish-notation 逆波兰表达式求值

150.evaluate-reverse-polish-notation 逆波兰表达式求值

时间:2022-08-16 20:14:47浏览次数:70  
标签:150 getTop reverse int stk push 求值 tmp1 tmp2

题目本身很简单,利用stack即可,注意string转换成int->std::stoi(s),以及先判断是不是运算符,再判断是什么运算符,可以节省时间。

#include <stack>
#include <string>
#include <vector>
using std::stack;
using std::string;
using std::vector;
class Solution {
  public:
    int evalRPN(vector<string> &tokens) {
        stack<int> stk;
        int tmp1, tmp2;
        for (string s : tokens) {
            if (s == "/" || s == "+" || s == "*" || s == "-") {
                if (s == "/") {
                    tmp1 = getTop(stk);
                    tmp2 = getTop(stk);
                    stk.push(tmp2 / tmp1);
                } else if (s == "+") {
                    tmp1 = getTop(stk);
                    tmp2 = getTop(stk);
                    stk.push(tmp2 + tmp1);
                } else if (s == "*") {
                    tmp1 = getTop(stk);
                    tmp2 = getTop(stk);
                    stk.push(tmp2 * tmp1);
                } else if (s == "-") {
                    tmp1 = getTop(stk);
                    tmp2 = getTop(stk);
                    stk.push(tmp2 - tmp1);
                }
            } else {
                int tmp = std::stoi(s);
                stk.push(tmp);
            }
        }
        return getTop(stk);
    }
    int getTop(stack<int> &st) {
        int temp = st.top();
        st.pop();
        return temp;
    }
};

标签:150,getTop,reverse,int,stk,push,求值,tmp1,tmp2
From: https://www.cnblogs.com/zwyyy456/p/16592801.html

相关文章