1. 程式人生 > 實用技巧 >0227. Basic Calculator II (M)

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)
}