LeetCode 224: Basic Calculator

Problem Description

Explanation

To solve this problem, we will use a stack to keep track of the operands and operators as we process the input expression. We will iterate through the string character by character and handle different cases such as digits, operators, and parentheses. By maintaining a running total and a sign value, we can calculate the result of the expression.

  1. Initialize a stack to store the operands and a variable result to store the final result.
  2. Initialize sign as 1 to represent the positive sign.
  3. Iterate through each character of the input string s.
  4. If the character is a digit, update the num variable.
  5. If the character is an operator (+ or -), update the result and sign accordingly.
  6. If the character is an opening parenthesis, push the current result and sign onto the stack and reset them.
  7. If the character is a closing parenthesis, calculate the result within the current parentheses and update the result and sign values.
  8. Finally, return the calculated result.

Time Complexity: O(n), where n is the length of the input string s. Space Complexity: O(n), where n is the length of the input string s.

Solutions

class Solution {
    public int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        int result = 0;
        int num = 0;
        int sign = 1;
        
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                num = num * 10 + (c - '0');
            } else if (c == '+') {
                result += sign * num;
                num = 0;
                sign = 1;
            } else if (c == '-') {
                result += sign * num;
                num = 0;
                sign = -1;
            } else if (c == '(') {
                stack.push(result);
                stack.push(sign);
                result = 0;
                sign = 1;
            } else if (c == ')') {
                result += sign * num;
                num = 0;
                result *= stack.pop(); // pop the sign
                result += stack.pop(); // add back the result outside the parentheses
            }
        }
        
        if (num != 0) {
            result += sign * num;
        }
        
        return result;
    }
}

Loading editor...