Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
题意为:
求逆波兰表达式的值
分析:
若当前字符是操作数,则压栈;
若当前字符是操作符,则弹出栈中的两个操作数,计算后仍然压入栈中。
解法:
class Solution {
public:
bool isOperator(const string &op)
{
string s="+-*/";
if(op.size()==1&&s.find(op)!=string::npos)
return true;
else
return false;
}
int str2int(string s)
{
int result=0;
int base=1;
for(int i=s.size()-1;i>=0;i--)
{
if(s[i]=='-'&&i==0)
result*=-1;
else if(s[i]>='0'&&s[i]<='9'){
result+=base*(s[i]-'0');
base*=10;
}
}
return result;
}
int evalRPN(vector<string>& tokens) {
stack<int> s;
for(auto token:tokens)
{
if(!isOperator(token))
s.push(str2int(token));
else{
int y=s.top();
s.pop();
int x=s.top();
s.pop();
if(token[0]=='+')
x+=y;
else if(token[0]=='-')
x-=y;
else if(token[0]=='*')
x*=y;
else if(token[0]=='/')
x/=y;
s.push(x);
}
}
return s.top();
}
};