Leetcode 224. Basic Calculator

本文介绍了一种使用栈从后向前遍历字符串来解析和计算数学表达式的算法。该方法适用于包含加减运算及括号的表达式,通过逆波兰表示法的思想实现,能够高效处理复杂的算术表达。

在这里插入图片描述
方法1: 从后往前遍历string,用一个stack。详细解释直接参考lc官方解答1。时间复杂n,空间复杂n,n为string的长度。

class Solution {
    public int calculate(String s) {
        if (s.charAt(0) == '-') s = "0" + s;
        int operand = 0;
        int n = 0;
        Stack<Object> stack = new Stack<>();
        
        for(int i = s.length()-1; i >= 0; i--){
            char c = s.charAt(i);
            if(Character.isDigit(c)){
                operand = (int)Math.pow(10, n) * (int)(c - '0') + operand;
                n++;
            }else if(c != ' '){
                if(n != 0){
                    stack.push(operand);
                    n = 0;
                    operand = 0;
                }
                if(c == '('){
                    int res = evaluateExpr(stack);
                    stack.pop();
                    stack.push(res);
                }else{
                    stack.push(c);
                }
            }
        }
        if(n != 0) stack.push(operand);
        return evaluateExpr(stack);
    }
    
    public int evaluateExpr(Stack<Object> stack){
        int res = 0;
        if(!stack.isEmpty()){
            res = (int) stack.pop();
        }
        
        while(!stack.isEmpty() && !((char)stack.peek() == ')')){
            char sign = (char) stack.pop();
            if(sign == '+'){
                res += (int) stack.pop();
            }else{
                res -= (int) stack.pop();
            }
        }
        return res;
    }
}

总结:

  • 还有一个方法2,自己去lc上看。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值