Algo-Sim › Stacks & Monotonic Stack
Basic Calculator
Hard · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input
Evaluate + − with parentheses: "(" saves the running result and the sign in front of it on a stack, ")" pops and combines.
Problem
Evaluate the string s, which contains non-negative integers, +, -, parentheses and spaces, and return the result. A - may be unary (at the start or right after (), but + never is. Built-in expression evaluators are not allowed.
Constraints
- 1 ≤ s.length ≤ 3 · 10⁵
- The expression is valid
- "+" is never unary; "-" can be unary
- Every number and running result fits in a 32-bit integer
Edge cases to test
- Unary minus:
"-(2 + 3)" - Nested parentheses
- Multi-digit numbers
Follow-up questions
- Why save the sign with the result?
- The sign in front of
(applies to the whole group, so)needs both the outer result and that sign: O(n) time, O(depth) stack. - How would you add × and ÷?
- Combine with Basic Calculator II’s last-term trick inside each parenthesis level (LC 772).
Solution
Java
public int calculate(String s) {
Deque<Integer> stack = new ArrayDeque<>();
int result = 0, num = 0, sign = 1;
for (char c : s.toCharArray()) {
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
} else if (c == '+' || c == '-') {
result += sign * num;
num = 0;
sign = c == '+' ? 1 : -1;
} else if (c == '(') {
stack.push(result);
stack.push(sign);
result = 0;
sign = 1;
} else if (c == ')') {
result += sign * num;
num = 0;
result = result * stack.pop() + stack.pop();
}
}
return result + sign * num;
}Python
def calculate(s):
stack = []
result, num, sign = 0, 0, 1
for c in s:
if c.isdigit():
num = num * 10 + int(c)
elif c in '+-':
result += sign * num
num = 0
sign = 1 if c == '+' else -1
elif c == '(':
stack.append(result)
stack.append(sign)
result = 0
sign = 1
elif c == ')':
result += sign * num
num = 0
result = result * stack.pop() + stack.pop()
return result + sign * numC++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int calculate(string s) {
stack<int> st;
int result = 0, num = 0, sign = 1;
for (char c : s) {
if (isdigit(c)) {
num = num * 10 + (c - '0');
} else if (c == '+' || c == '-') {
result += sign * num;
num = 0;
sign = c == '+' ? 1 : -1;
} else if (c == '(') {
st.push(result);
st.push(sign);
result = 0;
sign = 1;
} else if (c == ')') {
result += sign * num;
num = 0;
int saved = st.top();
st.pop();
result = result * saved + st.top();
st.pop();
}
}
return result + sign * num;
}
};
More Stacks & Monotonic Stack problems
- Valid Parentheses (Easy)
- Implement Queue using Stacks (Easy)
- Evaluate Reverse Polish Notation (Medium)
- Basic Calculator II (Medium)
- Decode String (Medium)
- Asteroid Collision (Medium)
- Next Greater Element (Easy)
- Daily Temperatures (Medium)
- Remove K Digits (Medium)
- Online Stock Span (Medium)
- Car Fleet (Medium)
- Largest Rectangle in Histogram (Hard)
- Maximal Rectangle (Hard)
- Sliding Window Maximum (Hard)