题解 | #后缀表达式求值# 直接用栈操作即可

后缀表达式求值

https://www.nowcoder.com/practice/22f9d7dd89374b6c8289e44237c70447


#include <cctype>
#include <string>
class Solution {
public:
    /**
     * 
     * @param tokens string字符串vector 
     * @return int整型
     */
    bool issymbol(string& str){
       if(str=="+"||str=="-"||str=="*"||str=="/"){
        return true;
       }
       return false;
    }
    int calculate(int& num1,int& num2,string s){
        if(s=="+"){
            return num2+num1;
        }
        else if(s=="-"){
            return num2-num1;
        }
        else if(s=="*"){
            return num2*num1;
        }
        else{
            return num2/num1;
        }

    }
    int evalRPN(vector<string>& tokens) {
        // write code here
        stack<int> s;
        int n=tokens.size();
        for(int i=0;i<n;i++){
            if(!issymbol(tokens[i])){
                int temp=stoi(tokens[i]);
                s.push(temp);
            }
            else{
                int num1=s.top();
                s.pop();
                int num2=s.top();
                s.pop();
                s.push(calculate(num1,num2,tokens[i]));
            }
        }
        return s.top();
    }
};

全部评论

相关推荐

“校招”、“3-5年经验”
xiaolihuam...:逆向工程不是搞外挂的吗,好像现在大学生坐牢最多的就是诈骗罪和非法侵入计算机系统罪,发美金,还居家办公,就是怕被一锅端,
点赞 评论 收藏
分享
深夜书店vv:腾讯是这样的,去年很多走廊都加桌子当工区
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务