LeetCode 150 Evaluate Reverse Polish Notation

标签: LeetCode 发布于:2022-03-02 17:24:25 编辑于:2022-03-02 18:31:52 浏览量:1052

概述

https://leetcode.com/problems/evaluate-reverse-polish-notation/

解法

用一个堆栈就好了。

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> s;
        for (auto t : tokens) {
            if (t == "+" || t == "-" || t == "*" || t == "/") {
                int r = s.top(); s.pop();
                int l = s.top(); s.pop();
                int res = 0;
                switch (t[0]) {
                    case '+':
                        res = l + r;
                        break;
                    case '-':
                        res = l - r;
                        break;
                    case '*':
                        res = l * r;
                        break;
                    case '/':
                        res = l / r;
                        break;                        
                }
                s.push(res);
            } else {
                s.push(stoi(t));
            }
        }
        return s.top();
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/