Leetcode 227. Basic Calculator II

在这里插入图片描述
方法1: 这道题相对于224来说稍微容易一点,因为不用考虑括号配对问题。思路大致也是使用一个stack,遍历整个string,如果遇到乘除法,直接把答案算出来,然后直接push进stack,整个过程中stack中只保存数字,这些数字最后全部加起来就是答案。具体解释直接看lc官方解答1,写得不错。时间复杂n,空间复杂n。

class Solution {
    public int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        int operand = 0;
        char operation = '+';
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            if(Character.isDigit(c)){
                operand = operand * 10 + (c - '0');
            }
            if(!Character.isDigit(c) && c != ' ' || i == s.length()-1){
                if(operation == '-'){
                    stack.push(-operand);
                } 
                if(operation == '+'){
                    stack.push(operand);
                }
                if(operation == '*'){
                    stack.push(stack.pop() * operand);
                }
                if(operation == '/'){
                    stack.push(stack.pop() / operand);
                }
                operation = c;
                operand = 0;
            }
        }
        int res = 0;
        while(!stack.isEmpty()){
            res += stack.pop();
        }
        return res;
    }
}

方法2: 不用stack,所以空间复杂1。这个方法看起来是方法1的优化,并且代码上变化也不大,但是其实逻辑上还是挺难理解的,我暂时不要求自己掌握。具体解释直接看lc官方解答2.

class Solution {
    public int calculate(String s) {
        if (s == null || s.isEmpty()) return 0;
        int length = s.length();
        int currentNumber = 0, lastNumber = 0, result = 0;
        char operation = '+';
        for (int i = 0; i < length; i++) {
            char currentChar = s.charAt(i);
            if (Character.isDigit(currentChar)) {
                currentNumber = (currentNumber * 10) + (currentChar - '0');
            }
            if (!Character.isDigit(currentChar) && !Character.isWhitespace(currentChar) || i == length - 1) {
                if (operation == '+' || operation == '-') {
                    result += lastNumber;
                    lastNumber = (operation == '+') ? currentNumber : -currentNumber;
                } else if (operation == '*') {
                    lastNumber = lastNumber * currentNumber;
                } else if (operation == '/') {
                    lastNumber = lastNumber / currentNumber;
                }
                operation = currentChar;
                currentNumber = 0;
            }
        }
        result += lastNumber;
        return result;
    }
}

总结:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值