classSolution { public: intcalculate(string s){ int n = s.length(); char last = ' '; stack<int> nums; stack<char> ops;
for (int i = 0; i < n; i++) { if (s[i] == ' ') continue; elseif (s[i] >= '0' && s[i] <= '9') { int num = 0; while (i < n && s[i] >= '0' && s[i] <= '9') { num = num * 10 + (s[i++] - '0'); } i--; nums.push(num); last = 'n'; } else { if (s[i] != '(' && last != 'n' && last != ')') nums.push(0); while (s[i] != '(' && !ops.empty() && ops.top() != '(') { char op = ops.top(); ops.pop(); int b = nums.top(); nums.pop(); int a = nums.top(); nums.pop(); if (op == '+') nums.push(a + b); elseif (op == '-') nums.push(a - b); } if (s[i] != ')') ops.push(s[i]); else ops.pop(); last = s[i]; } }
while (!ops.empty()) { char op = ops.top(); ops.pop(); int b = nums.top(); nums.pop(); int a = nums.top(); nums.pop(); if (op == '+') nums.push(a + b); elseif (op == '-') nums.push(a - b); }