Basic Calculator III

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 .

The expression string contains only non-negative integers, +-*/ operators , open ( and closing parentheses ) and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of [-2147483648, 2147483647].

Some examples:

"1 + 1" = 2
" 6-4 / 2 " = 4
"2*(5+5*2)/3+(6/2+8)" = 21
"(2+6* 3+5- (3*14/7+2)*5)+3"=-12

思路:这里跟calculator II很类似,不同的就是加入了括号,括号的处理可以用递归,找到左右边界,递归算出num;

注意后面是处理sign,也就是num之前的符号,+ push(num_, - push(-num), * push(pop() * num), / push(pop/ num);

其余的跟calculator II一模一样,都是把值算好了,丢到stack里面,最后把stack里面的东西sum起来就是答案;

中间找左右两个边界的,跟 1087 Brace Expansion 很类似;

class Solution {
    public int calculate(String s) {
        if(s == null || s.length() == 0) {
            return 0;
        }
        char sign = '+';
        int num = 0;
        int res = 0;
        Stack<Integer> stack = new Stack<>();
        int len = s.length();
        for(int i = 0; i < len; i++) {
            char c = s.charAt(i);
            //取数;
            if(Character.isDigit(c)) {
                num = num * 10 + c - '0';
            }
            // 每次是得到当前的运算符,计算之前的数和运算符,然后更新sign为当前的运算符;
            // 注意最后一个数字,由于符号总是在数字之前,所以最后一个数字没有办法计算,要单独列出来;
            if(!Character.isDigit(c) && c != ' ' || i == len - 1) {
                if(c == '(') {
                    int j = i; int count = 0;
                    for(; i < len; i++) {
                        if(s.charAt(i) == '(') {
                            count++;
                        }
                        if(s.charAt(i) == ')') {
                            count--;
                        }
                        if(count == 0) {
                            break;
                        }
                    }
                    // (      )
                    // j......i;
                    num = calculate(s.substring(j + 1, i));
                }
                if(sign == '+') {
                    stack.push(num);
                } else if(sign == '-') {
                    stack.push(-num);
                } else if(sign == '*') {
                    stack.push(stack.pop() * num);
                } else if(sign == '/') {
                    stack.push(stack.pop() / num);
                }
                num = 0;
                sign = c;
            }
        }
        for(int val: stack) {
            res += val;
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值