[LeetCode]Evaluate Reverse Polish Notation
来源:互联网 发布:ubuntu安装gnome2 编辑:程序博客网 时间:2024/05/20 14:23
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)) -> 6LeetCode 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(); }};
0 0
- Evaluate Reverse Polish Notation | leetcode
- 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
- Evaluate Reverse Polish Notation (LeetCode)
- leetcode: Evaluate Reverse Polish Notation
- Leetcode Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation -- LeetCode
- 【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
- 动态规划之01背包问题(最易理解的讲解)
- C查看分配给用户的内存及分配给系统的内存大小
- 使用hibernate运行产生的红字解决方法,虽然不影响,但是看着不爽
- VS2013(Win10X64)-配置编译Caffe
- Delphi 常用函数记录
- [LeetCode]Evaluate Reverse Polish Notation
- C字节对齐详解
- DNS BIND之nsupdate介绍和使用
- Java Socket重要参数讲解
- 第六周项目六(1)(2)
- Python字符串和字典相关操作
- Euresys eVision 加载和保存图像
- jquery为动态生成的元素添加点击事件
- 阻止putty变成inactive