class Solution {
public:
int solve(string s) {
stack<int>s1;
stack<char>s2;
s2.push('#');
bool fl=false;
int res=0;
for(auto x:s)
{
if(x>='0'&&x<='9')
{
if(fl)res=res*10+x-'0';
else res=x-'0';
fl=true;
}
else
{
if(fl)s1.push(res),res=0;
fl=false;
if(x=='(')s2.push('(');
else if(x==')')
{
while(s2.top()!='(')
{
char c=s2.top();
s2.pop();
int c2=s1.top(),c1;
s1.pop();
c1=s1.top();
s1.pop();
if(c=='*')s1.push(c1*c2);
else if(c=='+')s1.push(c1+c2);
else s1.push(c1-c2);
}
s2.pop();
}
else
{
if(x!='*')
{
while(s2.top()=='*'||s2.top()=='+'||s2.top()=='-')
{
char c=s2.top();
s2.pop();
int c2=s1.top(),c1;
s1.pop();
c1=s1.top();
s1.pop();
if(c=='*')s1.push(c1*c2);
else if(c=='+') s1.push(c1+c2);
else s1.push(c1-c2);
}
}
s2.push(x);
};
}
}
if(fl)s1.push(res);
while(s2.top()!='#')
{
char c=s2.top();
s2.pop();
int c2=s1.top(),c1;
s1.pop();
c1=s1.top();
s1.pop();
if(c=='*')s1.push(c1*c2);
else if(c=='+')s1.push(c1+c2);
else s1.push(c1-c2);
}
return s1.top();
}
};

京公网安备 11010502036488号