int calculate(string s) { // time: O(n); space: O(n)
if (s.empty()) return 0;
int n = s.length(), res = 0, num = 0;
char op = '+';
stack<int> st;
for (int i = 0; i < n; ++i) {
char c = s[i];
if (c >= '0' && c <= '9') num = num * 10 + (c - '0');
if (c == '+' || c == '-' || c == '*' || c == '/' || i == n - 1) {
if (op == '+') st.push(num);
else if (op == '-') st.push(-num);
else if (op == '*' || op == '/') {
int tmp = (op == '*') ? st.top() * num : st.top() / num;
st.pop();
st.push(tmp);
}
op = c;
num = 0;
}
}
while (!st.empty()) {
res += st.top();
st.pop();
}
return res;
}
int calculate(string s) { // time: O(n); space: O(1)
if (s.empty()) return 0;
int res = 0, curRes = 0, num = 0, n = s.length();
char op = '+';
for (int i = 0; i < n; ++i) {
char c = s[i];
if (c >= '0' && c <= '9') num = num * 10 + (c - '0');
if (c == '+' || c == '-' || c == '*' || c == '/' || i == n - 1) {
switch (op) {
case '+': curRes += num; break;
case '-': curRes -= num; break;
case '*': curRes *= num; break;
case '/': curRes /= num; break;
}
if (c == '+' || c == '-' || i == n - 1) {
res += curRes;
curRes = 0;
}
op = c;
num = 0;
}
}
return res;
}