772. Basic Calculator III
https://leetcode.com/problems/basic-calculator-iii/
class Solution {
public:
int calculate(string s) {
stack<long> nums;
stack<char> ops;
const auto higher = [](char a, char b) {
if ((a == '*' || a == '/') && (b == '+' || b == '-')) return true;
return false;
};
const auto op = [&]() {
const auto b = nums.top(); nums.pop();
const auto a = nums.top(); nums.pop();
const auto o = ops.top(); ops.pop();
switch (o) {
case '+':
nums.push(a + b);
break;
case '-':
nums.push(a - b);
break;
case '*':
nums.push(a * b);
break;
case '/':
nums.push(a / b);
break;
}
};
long num = 0;
for (int i = 0; i < s.length(); ++i) {
auto c = s[i];
if (isdigit(c)) {
num = c - '0';
while (i + 1 < s.length() && isdigit(s[i + 1])) {
num = num * 10 + (s[i + 1] - '0');
++i;
}
nums.push(num);
num = 0;
} else if (c == '(') {
ops.push(c);
if (s[i + 1] == '-') {
nums.push(0);
++i;
ops.push('-');
}
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
if (c == '-' && nums.empty()) {
nums.push(0);
ops.push(c);
continue;
}
while (!ops.empty() && ops.top() != '(' && !higher(c, ops.top())) {
op();
}
ops.push(c);
} else if (c == ')') {
while (!ops.empty() && ops.top() != '(') {
op();
}
ops.pop();
}
}
while (!ops.empty()) {
op();
}
return nums.top();
}
};Last updated