[Leetcode]_150 Evaluate Reverse Polish Notation

/**
 *  Index: 150
 *  Title: Evaluate Reverse Polish Notation
 *  Author: ltree98
 **/

题意

计算逆波兰式(逆波兰式也可称作后缀表示法,它将操作符置于操作数后面,这种方式不需要用括号来标识操作符的优先级)的值,合法的操作符有 + - * / ,每个操作数为一个整数或表达式。

注意:

  • 除法运算,需要向下取整
  • 给定的表达式一定合法。即一定会有个最终值,不会有除0等不合法行为

我的

思路

用栈结构,进行计算;注意 - / 运算符时,弹出栈操作数的位置顺序。

时间复杂度:O(n)
空间复杂度:O(n)

实现

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> answer;
        
        for(int i = 0; i < tokens.size(); i++)  {
            if(tokens[i][0] == '+') {
                int param1 = answer.top();
                answer.pop();
                int param2 = answer.top();
                answer.pop();
                answer.push(param1 + param2);
            }
            else if(tokens[i][0] == '-' && tokens[i].length() == 1) {
                int param1 = answer.top();
                answer.pop();
                int param2 = answer.top();
                answer.pop();
                answer.push(param2 - param1);
            }
            else if(tokens[i][0] == '*')    {
                int param1 = answer.top();
                answer.pop();
                int param2 = answer.top();
                answer.pop();
                answer.push(param1 * param2);
            }
            else if(tokens[i][0] == '/') {
                int param1 = answer.top();
                answer.pop();
                int param2 = answer.top();
                answer.pop();
                answer.push(param2 / param1);
            }    
            else    {
                int val = std::stoi(tokens[i]);   
                answer.push(val);
            }
        }
        
        return answer.top();
    }
};

进阶

思路

基本都是通过栈来做,非常标准的栈练习题;差别在于代码的简洁度不同。

比如用switch替换一堆if-elseif-else,或者用lambda。

实现

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        unordered_map<string, function<int (int, int) > > map = {
            { "+" , [] (int a, int b) { return a + b; } },
            { "-" , [] (int a, int b) { return a - b; } },
            { "*" , [] (int a, int b) { return a * b; } },
            { "/" , [] (int a, int b) { return a / b; } }
        };
        std::stack<int> stack;
        for (string& s : tokens) {
            if (!map.count(s)) {
                stack.push(stoi(s));
            } else {
                int op1 = stack.top();
                stack.pop();
                int op2 = stack.top();
                stack.pop();
                stack.push(map[s](op2, op1));
            }
        }
        return stack.top();
    }
};

author: hercule24

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值