题解 | 逆波兰表达式求值

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param tokens string字符串vector 
     * @return int整型
     */
    int evalRPN(vector<string>& tokens) {
        // write code here
        stack<int> s;
        int i = 0, n = tokens.size();
        int a, b;
        
        for(; i < n; i++){
            if(tokens[i]=="+" || tokens[i]=="-" || tokens[i]=="*" || tokens[i]=="/"){
                b = s.top();
                s.pop();
                a = s.top();
                s.pop();
                char op = tokens[i][0];
                if(op=='+')
                    s.push(a + b);
                else if(op=='-')
                    s.push(a-b);
                else if(op=='*')
                    s.push(a*b);
                else
                    s.push(a/b);
            }
            else {
                s.push(stoi(tokens[i]));//字符串转数字
            }
        }
        return s.top();
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务