leetcode150. 逆波兰表达式求值

本文介绍了一种计算逆波兰表达式的算法实现,通过使用栈结构处理输入的运算符和操作数,实现对复杂数学表达式的求值。文章提供了Python和Java两种语言的代码示例。

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

示例 1:

输入: ["2", "1", "+", "3", "*"]
输出: 9
解释: ((2 + 1) * 3) = 9
示例 2:

输入: ["4", "13", "5", "/", "+"]
输出: 6
解释: (4 + (13 / 5)) = 6
(a+b)*c-(a+b)/e的后缀表达式为:
(a+b)*c-(a+b)/e
→((a+b)*c)((a+b)/e)-
→((a+b)c*)((a+b)e/)-
→(ab+c*)(ab+e/)-
→ab+c*ab+e/-

思路:

首先声明一个栈stack,然后线性扫描input数组,

如果当前元素是运算符,就把栈的最上面两个元素进行相应运算,把它们俩弹出来,再把运算结果push进栈,

如果当前元素不是运算符,直接push就行了。

注意最后返回的结果要转换成int的形式,

而且除法需要只保留整数位。

  • python
class Solution(object):
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        stack = []
        for item in tokens:
            if item in ["+", "-", "*", "/"]:
                if item == "+":
                    temp = int(stack[-2]) + int(stack[-1])
                elif item == "-":
                    temp = int(stack[-2]) - int(stack[-1])
                    # print temp                
                elif item == "*":
                    temp = int(stack[-2]) * int(stack[-1])             
                elif item == "/":
                    temp = int(float(stack[-2])/ float(stack[-1]))                    
                stack.pop()
                stack.pop()
                stack.append(temp)
                
            else:
                stack.append(item)
                
        return int(stack[0])

class Solution {
    public int evalRPN(String[] tokens) {
      Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < tokens.length; i++) {
            switch (tokens[i]) {
                case "+":
                    stack.push(stack.pop() + stack.pop());
                    break;
                case "-":
                    int one = stack.pop();
                    int two = stack.pop();
                    stack.push(two - one);
                    break;
                case "*":
                    stack.push(stack.pop() * stack.pop());
                    break;
                case "/":
                    int t1 = stack.pop();
                    int t2 = stack.pop();
                    stack.push(t2 / t1);
                    break;
                default:
                    stack.push(Integer.parseInt(tokens[i]));
                    break;
            }
        }
        return stack.pop();  
    }
}
逆波兰式https://baike.baidu.com/item/%E9%80%86%E6%B3%A2%E5%85%B0%E5%BC%8F/128437
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值