Skip to content

Latest commit

 

History

History
58 lines (42 loc) · 1.12 KB

File metadata and controls

58 lines (42 loc) · 1.12 KB

Basic Calculator II

Problem Link

https://leetcode.com/problems/basic-calculator-ii/


Pattern

  • Stack
  • String

Approach

Scan the expression, keep the last operator, and use a stack to handle multiplication and division immediately.


Time Complexity

O(n)

Space Complexity

O(n)


Java Solution

import java.util.*;
class Solution {
    public int calculate(String s) {
        Stack<Integer> stack = new Stack<>();
        int num = 0;
        char sign = '+';
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) num = num * 10 + (c - '0');
            if ((!Character.isDigit(c) && c != ' ') || i == s.length() - 1) {
                if (sign == '+') stack.push(num);
                else if (sign == '-') stack.push(-num);
                else if (sign == '*') stack.push(stack.pop() * num);
                else if (sign == '/') stack.push(stack.pop() / num);
                sign = c;
                num = 0;
            }
        }
        int ans = 0;
        for (int n : stack) ans += n;
        return ans;
    }
}