[leetcode] Basic Calculator 使用堆栈计算表达式的值

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

Note: Do not use the eval built-in library function.


解题思路:

因为只存在加减法,只需要考虑表达式前的符号,全部使用加法完成计算即可;

遇到左括号,就把已经计算出的部分表达式结果值压栈,并把当前括号前的符号压栈,继续计算括号里的表达式;

遇到右括号,先把括号里的计算结果乘上栈顶保存着的括号的符号,弹出栈顶符号,再加上当前栈顶保存的上一部分的结果,组成总结果。


class Solution {
    public int calculate(String s) {
        
        int res = 0, sign = 1;
        
        String expression = s.replaceAll(" ","");
        
        int len = expression.length();
        
        Stack<Integer> stk = new Stack<>();
        
        for(int i=0;i<len;++i){
            
            char c = expression.charAt(i);
            
            if(c >= '0' && c <= '9'){
                int sum = 0;
                while(c >='0' && c <='9'){
                    sum = sum * 10 + (c - '0');
                    if(++i < len){
                        c = expression.charAt(i);
                    }else{
                        break;
                    }
                }
                res = res + sum * sign;
                i--; 
            }else if(c == '+'){
                sign = 1;
            }else if(c == '-'){
                sign = -1;
            }else if(c == '('){
                stk.push(res);
                stk.push(sign);
                res = 0;
                sign = 1; 
            }else if(c == ')'){
                res *= stk.pop();
                res += stk.pop();
            }
            
        }
        
        return res;
        
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值