题目描述
思路
采用后缀表达式的形式来做这道题,用两个堆栈存储数据。一个存储数字,一个存储运算符。循环历遍真个字符串。
- 如果是空格那么,跳到下一个字符。
- 如果是数字,那么压入存储数字的堆栈中。
- 如果是运算符的话,就需要判断。采用后缀表达式的思路来计算。
关于后缀表达式,可以网上搜一下。或者查看一下连接。
https://blog.csdn.net/Antineutrino/article/details/6763722
解答
class Solution {
public:
int calculate(string s) {
stack<int> num;
stack<char> str;
for(int i=0;i<s.size();++i)
{
if(' '==s[i]) continue;
if(s[i]-'0'<=9 && s[i]-'0'>=0) //用于处理数字
{
int temp=s[i]-'0';
int j=i+1;
while(j<s.size() && s[j]-'0'<=9 && s[j]-'0'>=0)//因为可能出现高位数字,不单单是0到9,还有可能是成百上千
{
temp=temp*10+(s[j]-'0');
j++;
}
i=j-1;
num.push(temp);
}
else //剩下的只有可能是运算符
{
if(str.empty())
{
str.push(s[i]);
}
else //若是存运算符的栈非空,那么就需要和之前存入的运算符比较优先级
{
//当前的运算符优先级高,继续压入
char pre=str.top();
if(('+'==pre || '-'==pre) && ('*'==s[i] ||'/'==s[i]))
{
str.push(s[i]);
}
else //和先前的运算符平级或者之前的运算符优先级高,取出运算
{
str.pop();
int num_1 = num.top();
num.pop();
int num_2 =num.top();
num.pop();
num.push(fun(num_1,num_2,pre));
//运算之后,仍然会存在平级,即同为加减级,再运算一次
if(!str.empty() && ('+'==s[i] ||'-'==s[i]))
{
char sign =str.top();
str.pop();
int num_1 = num.top();
num.pop();
int num_2 = num.top();
num.pop();
num.push(fun(num_1,num_2,sign));
}
str.push(s[i]);
}
}
}
}
while(!str.empty())
{
char sign = str.top();
str.pop();
int num_1 = num.top();
num.pop();
int num_2 = num.top();
num.pop();
num.push(fun(num_1,num_2,sign));
}
return num.top();
}
int fun(int num_1, int num_2, char str) //用于计算
{
if('*' == str) return num_1*num_2;
if('/' == str) return num_2/num_1;
if('+' == str) return num_1+num_2;
if('-' == str) return num_2-num_1;
}
};