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
这道题是要求依据算数表达式的逆波兰式(后缀表达式)求值。
栈的典型应用。
顺序读取算数表达式,推断读取的字符串表示的是运算数还是运算符。若是前者,则入栈,若是后者,则从栈顶弹出两个数,依据当前读取的运算符进行求值,并将结果入栈。反复上述步骤直至表达式结束。
在对字符串进行推断的时候,能够通过推断字符串的长度大于1或者第一个字符是数字来确定是不是运算数。
一開始想复杂了,以为运算数不仅仅是整数,还能够是小数,那么情况就有些复杂了:
1. 须要推断 “运算符”,“小数”。“整数”
2. 栈中元素的类型须要加以考虑,整数与整数,小数与小数,整数与小数的运算结果是不同的。
以下贴一个比較全面的对字符串是整数还是小数的推断:推断是否是整数,小数或实数
以下贴上代码:
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> opnd;
int a, b;
for (int i = 0; i < tokens.size(); i++){
if(isalnum(tokens[i][0])||tokens[i].length()>1){
opnd.push(atoi(tokens[i].c_str()));
}
else{
a = opnd.top();
opnd.pop();
b = opnd.top();
opnd.pop();
switch (tokens[i][0])
{
case '+':b=b+a; break;
case '-':b=b-a; break;
case '*':b=b*a; break;
case '/':b=b/a; break;
}
opnd.push(b);
}
}
return opnd.top();
}
};
版权声明:本文博客原创文章,博客,未经同意,不得转载。