Intuition
Process * and / immediately by popping the stack. Push results of + and - for later summation.
Explanation
Approach
- Parse numbers and operators.
- For + and -, push number (with sign) to stack.
- For * and /, pop top, compute, push result.
- Sum the stack for the final answer.
Complexity
- Time: O(n)
- Space: O(n)
Implementation
import java.util.*;
class Solution {
public int calculate(String s) {
Deque<Integer> stack = new ArrayDeque<>();
int num = 0;
char op = '+';
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
}
if (c == '+' || c == '-' || c == '*' || c == '/' || i == s.length() - 1) {
if (op == '+') stack.push(num);
else if (op == '-') stack.push(-num);
else if (op == '*') stack.push(stack.pop() * num);
else if (op == '/') stack.push(stack.pop() / num);
op = c;
num = 0;
}
}
int result = 0;
for (int n : stack) {
result += n;
}
return result;
}
}