首页 > 编程学习 > LeetCode 150. 逆波兰表达式求值

LeetCode 150. 逆波兰表达式求值

发布时间:2022/8/27 10:03:13

思路:
当字符串为运算符号是弹出栈中两个数字进行运算
stoi("1") 将string转换为int

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> stack;

        for (int i = 0; i < tokens.size(); i ++) {
            if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
                int num1 = stack.top();
                stack.pop();
                int num2 = stack.top();
                stack.pop();

                if (tokens[i] == "+") stack.push(num2 + num1);
                else if (tokens[i] == "-") stack.push(num2 - num1);
                else if (tokens[i] == "*") stack.push(num2 * num1);
                else stack.push(num2 / num1);
            }
            else stack.push(stoi(tokens[i]));
        }

        int res = stack.top();

        return res;
    }
};
Copyright © 2010-2022 mfbz.cn 版权所有 |关于我们| 联系方式|豫ICP备15888888号