题解 | 牛牛与后缀表达式
牛牛与后缀表达式
https://www.nowcoder.com/practice/a1a4f178f6ff4188890e51da1cc8ce10
#include <stack>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* 给定一个后缀表达式,返回它的结果
* @param str string字符串
* @return long长整型
*/
long long legalExp(string str) {
// write code here
stack<long long> stk;
long long a=0;
for(int i=0;i<str.size();i++)
{
if(str[i]>='0'&&str[i]<='9')
{
a = a*10 + (str[i]-'0');
}
else if(str[i]=='#')
{
stk.push(a);
a=0;
}
else if(str[i]=='+'&&!stk.empty())
{
long long sum=0;
sum+=stk.top();
stk.pop();
sum+=stk.top();
stk.pop();
stk.push(sum);
}
else if(str[i]=='-'&&!stk.empty())
{
long long sum=0;
sum-=stk.top();
stk.pop();
sum+=stk.top();
stk.pop();
stk.push(sum);
}
else if(str[i]=='*'&&!stk.empty())
{
long long sum=1;
sum*=stk.top();
stk.pop();
sum*=stk.top();
stk.pop();
stk.push(sum);
}
}
return stk.top();
}
};
查看30道真题和解析