逆波兰表示法

题目描述

根据逆波兰表示法,求表达式的值。
其实就是将中缀表达式转换成后缀表达式求值的过程。

说明:

  • 整数除法只保留整数部分。
  • 给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。

示例 1:

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

示例 2:

输入: ["4", "13", "5", "/", "+"]
输出: 6
解释: (4 + (13 / 5)) = 6

题目解析

用数据结构来解决这个问题。

  • 从前往后遍历数组
  • 遇到数字则压入栈中
  • 遇到符号,则把栈顶的两个数字拿出来运算,把结果再压入栈中
  • 遍历完整个数组,栈顶数字即为最终答案

代码实现

public static String[] a = {"2","3","5","*","+","2","-","4","2","/","+"};
    public static String soluation(){
        Stack<String> stack = new Stack();
        int length = a.length;
        int num = 0;
        for (int i = 0; i < length; i++) {
            switch (a[i]) {
                case "+":
                    if (stack.isEmpty() || stack.size() < 2) {

                        throw new RuntimeException("the expression is error");
                    }
                    num = StringToInt(stack.pop());
                    stack.push(intToString(StringToInt(stack.pop()) + num));

                    break;
                case "-":
                    if (stack.isEmpty() || stack.size() < 2) {
                        throw new RuntimeException("the expression is error");
                    }
                    num = StringToInt(stack.pop());
                    stack.push(intToString(StringToInt(stack.pop()) - num));
                    break;
                case "*":
                    if (stack.isEmpty() || stack.size() < 2) {
                        throw new RuntimeException("the expression is error");
                    }
                    num = StringToInt(stack.pop());
                    stack.push(intToString(StringToInt(stack.pop()) * num));
                    break;
                case "/":
                    if (stack.isEmpty() || stack.size() < 2) {
                        throw new RuntimeException("the expression is error");
                    }
                    num = StringToInt(stack.pop());
                    stack.push(intToString(StringToInt(stack.pop()) / num));
                    break;
                    default:
                        stack.push(a[i]);
                        break;
            }
        }
        return stack.pop();
    }

复杂度计算

空间需要一个辅助的栈结构,大小不会超过n,所以空间复杂度为O(n)。
时间复杂度只需要遍历完整个表达式就可以结束,所以时间复杂度为O(n)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值