227. Basic Calculator II (M)

Basic Calculator II (M)

Implement a basic calculator to evaluate a simple expression string.

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

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

Note:

  • You may assume that the given expression is always valid.
  • Do not use the eval built-in library function.

题意

计算只包含+, -, *, /和空格的数学表达式的值。

思路

方法一:从后向前遍历字符串,遇空格跳过,遇*, /压入操作符栈中,遇数字压入操作数栈中,遇’+’, '-'需要进行判断:如果操作符栈栈顶为*/,则从操作数栈和操作符栈分别出栈,将计算结果压回操作数栈,重复上述过程直到操作符栈为空或其栈顶为+, -,再将当前的+, -压入操作符栈中;其余情况则直接将+, -压入操作符栈中。全部遍历完后,重复出栈操作数栈和操作符栈计算结果即可。

方法二:从前向后遍历,参考自 [LeetCode] 227. Basic Calculator II 基本计算器之二


代码实现 - 从后向前遍历

class Solution {
    public int calculate(String s) {
        Deque<Integer> nums = new ArrayDeque<>();
        Deque<Character> ops = new ArrayDeque<>();

        for (int i = s.length() - 1; i >= 0; i--) {
            char c = s.charAt(i);
            if (c == ' ') {
                continue;
            } else if (c == '+' || c == '-') {
                while (!ops.isEmpty() && (ops.peek() == '*' || ops.peek() == '/')) {
                    int a = nums.pop();
                    int b = nums.pop();
                    char op = ops.pop();
                    int cal = op == '*' ? a * b : a / b;
                    nums.push(cal);
                }
                ops.push(c);
            } else if (c == '*' || c == '/') {
                ops.push(c);
            } else {
                int num = c - '0';
                int zeros = 10;
                while (i - 1 >= 0 && s.charAt(i - 1) <= '9' && s.charAt(i - 1) >= '0') {
                    num = (s.charAt(i - 1) - '0') * zeros + num;
                    zeros *= 10;
                    i--;
                }
                nums.push(num);
            }
        }

        while (nums.size() != 1) {
            int a = nums.pop();
            int b = nums.pop();
            char op = ops.pop();
            int cal = (op == '+' ? a + b : op == '-' ? a - b : op == '*' ? a * b : a / b);
            nums.push(cal);
        }

        return nums.pop();
    }
}

代码实现 - 从前向后遍历

class Solution {
    public int calculate(String s) {
        Deque<Integer> stack = new ArrayDeque<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == ' ') {
                continue;
            } else if (c == '*' || c == '/') {
                int a = stack.pop();
                int b = 0;
                while (!(s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9')) {
                    i++;
                }
                while (i + 1 < s.length() && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9') {
                    b = b * 10 + s.charAt(i + 1) - '0';
                    i++;
                }
                stack.push(c == '*' ? a * b : a / b);
            } else if (c == '+' || c == '-') {
                int num = 0;
                while (!(s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9')) {
                    i++;
                }
                while (i + 1 < s.length() && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9') {
                    num = num * 10 + s.charAt(i + 1) - '0';
                    i++;
                }
                stack.push(c == '+' ? num : -num);
            } else {
                int num = c - '0';
                while (i + 1 < s.length() && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '9') {
                    num = num * 10 + s.charAt(i + 1) - '0';
                    i++;
                }
                stack.push(num);
            }
        }
        while (stack.size() != 1) {
            stack.push(stack.pop() + stack.pop());
        }
        return stack.pop();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值