224. Basic Calculator

In this article, we will implement a basic calculator with addition and subtraction, which can also dealing with parentheses. To simplify the implementation, we assume the given expression is always valid, which contains only digits, positive sign, negative sign, and space.

class Solution {
    public int calculate(String s) {
        // init
        int sign = 1;
        int res = 0;
        
        LinkedList<Integer> stack = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                // the current digit
                int temp = c - '0';
                // if the following characters are digit, add them all
                while (i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))) {
                    temp = temp * 10 + (s.charAt(i + 1) - '0');
                    i++;
                }
                res += sign * temp;
            } else if (c == '+') {
                sign = 1;
            } else if (c == '-') {
                sign = -1;
            } else if (c == '(') {
                // (BOTTOM) res ->         (TOP)
                // (BOTTOM) res -> sign -> (TOP)
                stack.addLast(res);
                stack.addLast(sign);
                // reset sign and result
                sign = 1;
                res = 0;
            } else if (c == ')') {
                // res = sign * current_res + previous_res
                res = stack.removeLast() * res + stack.removeLast();
            } else {
                // space: ignore it
            }
        }
        return res;
    }
}

We can also use the Shunting-yard algorithm to convert the infix expression to postfix expression, then solve the postfix expression.

Reference

https://leetcode.com/problems/basic-calculator/discuss/62362/JAVA-Easy-Version-To-Understand!!!!!