这个代码是参考了评论区的题解,一变读取一遍计算,使用prev_op来实现减号的变化。
比之前的中缀转后缀再计算要快得多
这个是之前的版本https://blog.youkuaiyun.com/dyyzlzc/article/details/104337379
class Solution
{
public:
int calculate(string s)
{
s+="#";
char op = '+';
list<int> nums;
int *num = nullptr;
for (auto ch : s)
{
if (ch == ' ')
continue;
if (ch <= '9' && ch >= '0')
{
if (num == nullptr)
{
num=new int;
(*num) = ch - '0';
}
else
{
(*num) = (*num) * 10 + (ch - '0');
}
continue;
}
if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch=='#')
{
if (op == '+')
{
nums.push_back(*num);
}
else if (op == '-')
{
nums.push_back(-(*num));
}
else if (op == '*')
{
int r = nums.back();
nums.pop_back();
r *= *num;
nums.push_back(r);
}
else if(op=='/')
{
int r = nums.back();
nums.pop_back();
r /= *num;
nums.push_back(r);
}else{
nums.push_back(*num);
break;
}
delete num;
num=nullptr;
op=ch;
}
}
return accumulate(nums.begin(),nums.end(),0);
}
};