leetcode-150-Evaluate Reverse Polish Notation
来源:互联网 发布:mac怎么输入法 编辑:程序博客网 时间:2024/05/19 22:59
问题
题目:[leetcode-150]
思路
典型栈的应用,后缀表达式计算。
枚举每一个token,对于每一个token执行如下操作:
- 如果是操作数,进栈
- 如果是操作符,从操作数栈中弹出两个元素,进行计算,中间结果入操作数栈
最后操作数栈中的结果就是最终结果
代码
class Solution {public: int evalRPN(vector<string>& tokens) { int sz = tokens.size(); if(!sz) return 0; std::stack<int> opnd; int flag=0; for(int i = 0; i < sz; ++i){ if(flag=is_optr(tokens[i])){ // 操作符-弹出两操作数计算入栈 int right = opnd.top(); opnd.pop(); int left = opnd.top(); opnd.pop(); int tmp = cal_exp(flag, left, right); opnd.push(tmp); } else // 操作数-进栈 { int val = string_to_int(tokens[i]); opnd.push( val ); } } return opnd.top(); }private: int string_to_int(const std::string& num){ std::stringstream ss; ss << num; int ret; ss >> ret; return ret; } int is_optr(const std::string& s){ if( s == "+" ) return 1; else if( s=="-" ) return 2; else if( s=="*" ) return 3; else if( s=="/" ) return 4; else return 0; } int cal_exp(int flag, int left, int right){ int ans = 0; switch(flag){ case 1 : ans = left + right;break; case 2 : ans = left - right;break; case 3 : ans = left * right;break; case 4 : ans = left / right;break; default : break; } return ans; }};
0 0
- LeetCode 150 Evaluate Reverse Polish Notation
- LeetCode: Evaluate Reverse Polish Notation [150]
- LeetCode(150) Evaluate Reverse Polish Notation
- [leetcode 150] Evaluate Reverse Polish Notation
- [LeetCode 150]Evaluate Reverse Polish Notation
- Leetcode 150:Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation - LeetCode 150
- LeetCode---(150)Evaluate Reverse Polish Notation
- [Leetcode 150, Medium] Evaluate Reverse Polish Notation
- leetcode[150]:Evaluate Reverse Polish Notation
- LeetCode(150) Evaluate Reverse Polish Notation
- [leetcode-150]Evaluate Reverse Polish Notation(c++)
- leetcode 150: Evaluate Reverse Polish Notation
- 【leetcode】No.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
- MemCache超详细解读
- 在Java中使用Jedis操作Redis,在高并发的情况下,应用卡死、报无法获取连接错误的处理方式
- 字典序
- Android:关于mediacodec编码camera yuv数据帧率过低的问题
- webpack入门
- leetcode-150-Evaluate Reverse Polish Notation
- Codeforces 557B Pasha and Tea【二分+思维】
- 树莓派3B安装Chromium
- 二维码 ThoughtWorks.QRCode 简单使用实例
- 如何关闭TortoiseSVN的TSVNCache.exe进程
- vs2010软件使用总结
- public、private、protected区别-访问权限
- 重温Java基础之Java程序流程控制(二)
- STL的应用