leetcode No150. Evaluate Reverse Polish Notation
来源:互联网 发布:软件开发图片 编辑:程序博客网 时间:2024/06/11 20:36
Question
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
Algorithm
逆波兰表达式求值,用栈解决问题,我还在Solutions中看到了lambda表达式的解法,很有趣
https://discuss.leetcode.com/topic/38178/fancy-c-lambda-expression-solution
Accepted Code
一般解法:
class Solution {public: int evalRPN(vector<string>& tokens) { stack<int> s; for(int i=0;i<tokens.size();i++) { if(tokens[i]!="+"&&tokens[i]!="-"&&tokens[i]!="*"&&tokens[i]!="/") { s.push(stoi(tokens[i])); } else { int b=s.top(); s.pop(); int a=s.top(); s.pop(); if(tokens[i]=="+") s.push(a+b); else if(tokens[i]=="-") s.push(a-b); else if(tokens[i]=="*") s.push(a*b); else s.push(a/b); } } return s.top(); }};
lambda表达式解法
class Solution {public: int evalRPN(vector<string>& tokens) { unordered_map<string,function<int (int,int)>> hash={ {"+",[](int a,int b){return a+b;}}, {"-",[](int a,int b){return a-b;}}, {"*",[](int a,int b){return a*b;}}, {"/",[](int a,int b){return a/b;}}, }; stack<int> s; for(auto i:tokens) { if(hash[i]==0) { s.push(stoi(i)); } else { int b=s.top(); s.pop(); int a=s.top(); s.pop(); s.push(hash[i](a,b)); } } return s.top(); }};
阅读全文
0 0
- leetcode No150. Evaluate Reverse Polish Notation
- No150-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
- 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
- android4.4如何不保存连接验证失败的WiFi热点
- leetcode 575. Distribute Candies
- centos开启telnet服务
- 1Z0-051 37. You issued the following command to drop the PRODUCTS table:
- springMVC工作原理
- leetcode No150. Evaluate Reverse Polish Notation
- dbutils 介绍与使用
- Hibernate5的hibernate.cfg.xml基本配置
- Uva 933 Product of digits
- 熊猫TV技术与直播技术相关
- 有序数组增删改查找
- codevs 1198 NOIP 2012 国王的游戏 高精度 解题报告
- 再看Java泛型
- android 九宫格手势密码 纯代码实现