Approach
This problem is not hard but need to consider some special conditions.
I found that actually we just need to trace the actual sign after removing the parantheses. For instance, 1-(2-(3+4)) is equal to 1-2+3+4, so we need to buffer the current actual sign when we get the (. In this case, we stack - when getting the first (, and when approaching the second (, we know that it is negative outside, and this is negative so we need to invert the sign inside this parantheses, so stack + inside. And the sign is removed after ) is encountered.
Code
class Solution {
public:
int calculate(string s) {
stack<bool> stk;
stk.push(true);
bool pos = true;
bool sign = true; // T: +, F: -
long long num = 0;
long long ans = 0;
bool update = false;
for(const char& c: s) {
if(c == ' ') {
continue;
} else if(c == '(') {
stk.push(!(stk.top() ^ sign));
sign = true;
continue;
} else if(c == ')') {
if(update) updateAns(num, stk, ans, sign);
update = false;
stk.pop();
} else if(c == '-') {
if(update) updateAns(num, stk, ans, sign);
update = false;
sign = false;
} else if(c == '+') {
if(update) updateAns(num, stk, ans, sign);
update = false;
sign = true;
} else {
num *= 10;
num += (c - '0');
update = true;
}
}
if(update) updateAns(num, stk, ans, sign);
return ans;
}
void updateAns(long long& num, stack<bool>& stk, long long& ans, bool& sign) {
bool add = !(stk.top() ^ sign);
ans += (add ? num : -num);
num = 0;
}
};