[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:
LeetCode Source
分析:很简单的利用堆栈来实现,当读入数字时放入栈,读入符号时出栈。
特别注意数字出栈的顺序。这个例子的Corner Case比较简单。
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(); } };
相关文章推荐
- leetcode_Evaluate Reverse Polish Notation
- 《leetCode》:Evaluate Reverse Polish Notation
- LeetCode Reverse Words in a String & Evaluate Reverse Polish Notation
- (leetcode)Evaluate Reverse Polish Notation
- LeetCode-150. Evaluate Reverse Polish Notation (JAVA)逆波兰表达式求值
- [LeetCode] Evaluate Reverse Polish Notation 计算逆波兰表达式
- [LeetCode] Evaluate Reverse Polish Notation, Solution
- 【LeetCode】Evaluate Reverse Polish Notation
- LeetCode | Evaluate Reverse Polish Notation
- 【Leetcode】Evaluate Reverse Polish Notation
- leetcode--evaluate-reverse-polish-notation
- LeetCode Evaluate Reverse Polish Notation
- leetcode之Evaluate Reverse Polish Notation
- LeetCode Evaluate Reverse Polish Notation
- 【LeetCode】Evaluate Reverse Polish Notation
- LeetCode | Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- LeetCode_evaluate-reverse-polish-notation
- LeetCode算法题目:Evaluate Reverse Polish Notation
- LeetCode 150. Evaluate Reverse Polish Notation