题解:后缀表达式一把嗦
class Solution {
public:
string s1[1000005];
string s2[1000005];
int s3[1000005];
int top1;
int top2;
int top3;
int calculate(string s) {
top1=0;top2=0;top3=0;
string str="";
for(int i=0;i<s.length();i++)
{
if(s[i]>='0'&&s[i]<='9')
{
str+=s[i];
continue;
}
if(str!="")
{
s2[top2++] = str;
str="";
}
if(s[i]==' ') continue;
if(s[i]=='(')
{
s1[top1++] = s[i];
}
else if(s[i]=='+'||s[i]=='-')
{
if(top1==0||s1[top1-1]=="(")
{
s1[top1++]=s[i];
}
else
{
s2[top2++]=s1[top1-1];
top1--;
s1[top1++]=s[i];
}
}
else if(s[i]==')')
{
if(s1[top1-1]!="(")
{
s2[top2++]=s1[top1-1];
top1-=2;
}
else
{
top1--;
}
}
}
if(str!="")
s2[top2++]=str;
while(top1!=0)
{
s2[top2++]=s1[top1-1];
top1--;
}
for(int i=0;i<top2;i++)
{
if(s2[i]=="+")
{
int x =s3[top3-2]+s3[top3-1];
top3-=2;
s3[top3++]=x;
}
else if(s2[i]=="-")
{
int x =s3[top3-2]-s3[top3-1];
top3-=2;
s3[top3++]=x;
}
else
{
s3[top3++]=atoi(s2[i].c_str());
}
}
return s3[0];
}
};