[LeetCode]Evaluate Reverse Polish Notation

本文介绍了一种通过栈来解决逆波兰表达式求值问题的方法,并提供了详细的算法实现步骤及C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Question:

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
思路:新建一个stack,然后遍历表达式,如果是数字就入栈,如果是操作符,就从栈中取出栈顶的两个数字(并pop())进行计算,然后将计算结果入栈。最后栈内剩余的最后一个数字就是需要return的结果。

另外也可以用表达式树实现,由后序遍历转换成中序遍历。

Answer:

class Solution {
public:
    int evalRPN(vector<string> &tokens) {
        stack<int> result;
        for (vector<string>::iterator it = tokens.begin(); it != tokens.end(); it++)
        {
            if (*it == "+" || *it == "-" || *it == "*" || *it == "/")
            {
                int temp1 = result.top(); result.pop();
                int temp2 = result.top(); result.pop();
                result.push( compute(temp1, temp2, *it) );
            }
            else
            {
                result.push(stoi(*it));
            }
        }
        return result.top();
    }
    int compute(int temp1, int temp2, string opt)
    {
        if(opt == "+") return temp2 + temp1;
        else if(opt == "-") return temp2 - temp1;
        else if(opt == "*") return temp2 * temp1;
        else return temp2 / temp1;
    }
    
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值