题目描述
思路分析
表达式计算题,栈的应用
可以作为模板题
代码实现
class Solution {
public:
typedef long long LL;
int calculate(string rs) {
string s;
for(auto ch:rs) if(ch!=' ') s+=ch;
stack<LL> num;
stack<char> op;
for(int i=0;i<s.size();i++){
auto ch=s[i];
if(ch==' ') continue;
if(isdigit(ch)){
LL cur=0,j=i;
while(j<s.size()&&isdigit(s[j])) cur=cur*10+s[j++]-'0';
num.push(cur);
i=j-1;
}
else if(ch=='('){
op.push(ch);
}
else if(ch==')'){
while(op.top()!='(') eval(num,op);
op.pop();
}
else{
if(!i||s[i-1]=='('||s[i-1]=='+'||s[i-1]=='-') num.push(0);
while(op.size()&&op.top()!='(') eval(num,op);
op.push(ch);
}
}
while (op.size()) eval(num, op);
return num.top();
}
void eval(stack<LL>& num,stack<char>& op){
auto b=num.top();num.pop();
auto a=num.top();num.pop();
auto c=op.top();op.pop();
if(c=='+') num.push(a+b);
else num.push(a-b);
}
};