1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| class Solution { public: int calculate(string s) { stack<int> stk; int cur = 0, sign = 1, ans = 0; for (char c : s) { if (c == ' ') continue; else if (c == '+') { ans += sign * cur; cur = 0; sign = 1; } else if (c == '-') { ans += sign * cur; cur = 0; sign = -1; } else if (c == '(') { stk.push(ans); stk.push(sign); ans = 0; sign = 1; } else if (c == ')') { ans += sign * cur; cur = 0; ans *= stk.top(); stk.pop(); ans += stk.top(); stk.pop(); } else { cur = cur * 10 + (c - '0'); } } if (cur != 0) ans += sign * cur; return ans; } };
|