0227. 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 基本计算器之二


代码实现

Java

从后向前遍历

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<>();
        int factor = 1;
        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 == '-') {
                factor = c == '+' ? 1 : -1;
            } 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 * factor);
            }
        }
        while (stack.size() != 1) {
            stack.push(stack.pop() + stack.pop());
        }
        return stack.pop();
    }
}

JavaScript

/**
 * @param {string} s
 * @return {number}
 */
var calculate = function (s) {
  let nums = []
  let op = 1
  let i = 0
  let reg = /[0-9]/

  while (i < s.length) {
    if (reg.test(s[i])) {
      let num = parseInt(s[i])
      while (++i < s.length && reg.test(s[i])) {
        num = num * 10 + parseInt(s[i])
      }
      nums.push(op * num)
    } else if (s[i] === '+' || s[i] === '-') {
      op = s[i++] === '+' ? 1 : -1
    } else if (s[i] === '*' || s[i] === '/') {
      let c = s[i]
      let A = nums.pop()
      while (s[++i] === ' ') {}
      let B = parseInt(s[i])
      while (++i < s.length && reg.test(s[i])) {
        B = B * 10 + parseInt(s[i])
      }
      nums.push(c === '*' ? A * B : Math.trunc(A / B))
    } else {
      i++
    }
  }

  return nums.reduce((acc, cur) => acc + cur)
}
原文地址:https://www.cnblogs.com/mapoos/p/14031520.html