LeetCode 227. Basic Calculator II(后缀表达式)
后缀表达式一把嗦。
class Solution {
public:
int s1[1000005];
int 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++] = atoi(str.c_str());
str="";
}
if(s[i]==' ') continue;
if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/')
{
if(top1==0)
{
s1[top1++]=change(s[i]);
}
else
{
while(top1>=1&&judge(change2(s1[top1-1]),s[i]))
{
s2[top2++]=s1[top1-1];
top1--;
}
s1[top1++]=change(s[i]);
}
}
}
if(str!="")
s2[top2++]=atoi(str.c_str());
while(top1!=0)
{
s2[top2++]=s1[top1-1];
top1--;
}
for(int i=0;i<top2;i++)
{
if(s2[i]==-1)
{
int x =s3[top3-2]/s3[top3-1];
top3-=2;
s3[top3++]=x;
}
else if(s2[i]==-2)
{
int x =s3[top3-2]*s3[top3-1];
top3-=2;
s3[top3++]=x;
}
else if(s2[i]==-3)
{
int x =s3[top3-2]-s3[top3-1];
top3-=2;
s3[top3++]=x;
}
else if(s2[i]==-4)
{
int x =s3[top3-2]+s3[top3-1];
top3-=2;
s3[top3++]=x;
}
else
{
s3[top3++]=s2[i];
}
}
return s3[0];
}
int change(char x)
{
if(x=='+')
return -4;
else if(x=='-')
return -3;
else if(x=='*')
return -2;
else
return -1;
}
char change2(int x)
{
if(x==-1)
return '/';
else if(x==-2)
return '*';
else if(x==-3)
return '-';
else
return '+';
}
int judge(char x,char y)
{
if(x=='+'||x=='-')
{
if(y=='+'||y=='-')
return 1;
if(y=='*'||y=='/')
return 0;
}
if(x=='*'||x=='/')
{
if(y=='+'||y=='-')
return 1;
if(y=='*'||y=='/')
return 1;
}
return 0;
}
};