您的位置:首页 > 编程语言 > Lua

[LeetCode]Evaluate Reverse Polish Notation

2015-04-19 12:33 295 查看
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

LeetCode Source

分析:很简单的利用堆栈来实现,当读入数字时放入栈,读入符号时出栈。

特别注意数字出栈的顺序。这个例子的Corner Case比较简单。

class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
for(int i=0;i<tokens.size();++i){
if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/")
{
//if(stk.size()<2){
//    return 0;
// }
int b = stk.top();
stk.pop();
int a = stk.top();
stk.pop();
if(tokens[i]=="+")
stk.push(a+b);
if(tokens[i]=="-")
stk.push(a-b);
if(tokens[i]=="/"){
// if(b==0)
//  return 0;
// else
stk.push(a/b);
}
if(tokens[i]=="*")
stk.push(a*b);
}
else stk.push(stoi(tokens[i]));
}
//if(stk.size()!=1)
// return 0;
//else
return stk.top();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: