Leetcode 150. Evaluate Reverse Polish Notation
来源:互联网 发布:程序员老黄历 runjs.cn 编辑:程序博客网 时间:2024/06/06 14:09
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
s思路:
1. 一看结构,就是需要用stack。例如: [“4”, “13”, “5”, “/”, “+”] ,把遇到的数先放进stack,所以当遇到”/”时,stack里面有三个数:4,13,5。遇到”/”,表示取stack 前面的2个数做除法,所以13/5=2,然后把2放进stack;当遇到”+”时,表示取stack 前面的2个数做加法,所以4+2=6,然后把6放进stack
2. 当然stack可以用vector来替代。
class Solution {public: int evalRPN(vector<string>& tokens) { // vector<int> res; for(string s:tokens){ if(s=="+"||s=="-"||s=="*"||s=="/"){ int op2=res.back(); res.pop_back(); int op1=res.back(); res.pop_back(); if(s=="+") res.push_back(op1+op2); else if(s=="-") res.push_back(op1-op2); else if(s=="*") res.push_back(op1*op2); else if(s=="/"){ res.push_back(op1/op2); } }else res.push_back(stoi(s)); } return res.front(); }};
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
- oracle11gR2的数据库示例用户安装说明
- 关于对 Unity 3D Strange IoC 框架事件分发器的认识
- requestlayout,onlayout,onDraw,invalidate区别与联系
- 九度 oj 题目1043:Day of Week
- AndroidStudio使用技巧
- Leetcode 150. Evaluate Reverse Polish Notation
- Zabbix_LLD_过滤监控项
- linux下利用freetds 访问sqlserver数据库
- iOS 面试题
- butterknife和lambda冲突,空指针
- Android动画效果translate、scale、alpha、rotate详解
- 《Android群英传》读书笔记1.Android体系与系统架构
- Java获取随机数的几种方法总结
- android插件化small框架初探(一)