[LeetCode]150. Evaluate Reverse Polish Notation
来源:互联网 发布:邓肯科比历史地位知乎 编辑:程序博客网 时间:2024/06/06 12:29
150. Evaluate Reverse Polish Notation
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
分析:思路比较简单,逆波兰表达式就是后缀表达式,遍历表达式,碰到数字就入栈,碰到操作符就出栈两个数字进行运算,运算结果再次入栈,直至遍历完毕。
class Solution {public: // 判断是否是操作符 bool isOp(string s){ return (s == "*" || s == "+" || s == "-" || s == "/") ? true : false; } // 计算 int calc(string op, int a, int b){ if(op == "+") return a + b; else if(op == "-") return a - b; else if(op == "/") return a / b; else return a * b; return 0; } int evalRPN(vector<string>& tokens) { // 逆波兰表达式是后缀表达式,先将其转换为中序表达式 if(tokens.size() == 0) return 0; if(tokens.size() == 1) return atoi(tokens[0].c_str()); stack<int> s; int right = 0; int left = 0; for(int i = 0; i < tokens.size(); ++i){ if(isOp(tokens[i])){ // 碰到操作符就出栈两个数字,进行运算,并将结果入栈 right = s.top(); s.pop(); left = s.top(); s.pop(); s.push(calc(tokens[i], left, right)); }else{ s.push(atoi(tokens[i].c_str())); // 如果是数字,转成int压入栈中 } } return s.top(); }};
阅读全文
0 0
- LeetCode 150. Evaluate Reverse Polish Notation
- [leetcode] 150.Evaluate Reverse Polish Notation
- 【leetcode】150. Evaluate Reverse Polish Notation
- Leetcode 150. Evaluate Reverse Polish Notation
- [LeetCode]150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation LeetCode
- Leetcode 150. Evaluate Reverse Polish Notation
- leetcode 150. Evaluate Reverse Polish Notation
- LeetCode 150. Evaluate Reverse Polish Notation
- LeetCode *** 150. Evaluate Reverse Polish Notation
- leetcode-150. Evaluate Reverse Polish Notation
- LeetCode-150.Evaluate Reverse Polish Notation
- leetcode.150. Evaluate Reverse Polish Notation
- LeetCode 150. Evaluate Reverse Polish Notation
- [leetcode] 150. Evaluate Reverse Polish Notation
- [leetcode] 【栈】150. Evaluate Reverse Polish Notation
- LeetCode - 150. Evaluate Reverse Polish Notation
- [LeetCode] 150. Evaluate Reverse Polish Notation
- Spring4 + Hibernate4 + SpringMVC 注解方式实现的双数据源(MySQL+SQLServer)
- web性能优化 高性能网站建设指南
- 解决远程桌面连接凭据不工作的问题
- 前端框架Vue(13)——vue 中如何对公共css、 js 方法进行单文件统一管理,全局调用
- 设计模式
- [LeetCode]150. Evaluate Reverse Polish Notation
- 小白学tkinter(多选按钮Checkbutton)
- C++ set的一些用法
- 查询数据库内存
- Git总结
- 练习之js继承的封装
- iOS开发 Swift3.0 Error
- RF+Appium环境配置四:ADB 配置(Setup_ADB_Server)
- HDU 6058 Kanade's sum