思路:用栈来模拟括号,栈中的元素只可能为1or-1以此来进行加减
class Solution {
public:
int calculate(string s) {
stack<int> temp;
temp.push(1);
int sign = 1;
int ret = 0;
int n = s.length();
int i = 0;
while (i < n)
{
if (s[i] == ' ')
{
i++;
}
else if (s[i] == '+')
{
sign = temp.top();
i++;
}
else if (s[i] == '-')
{
sign = -temp.top();
i++;
}
else if (s[i] == '(')
{
temp.push(sign);
i++;
}
else if (s[i] == ')')
{
temp.pop();
i++;
}
else
{
long num = 0;
while (i < n && s[i] >= '0' && s[i] <= '9') //防止两位数的加减
{
num = num * 10 + s[i] - '0';
i++;
}
ret += sign * num;//用栈中的元素来模拟加减
}
}
return ret;
}
};