【leetcode】Evaluate Reverse Polish Notation
来源:互联网 发布:nginx 域名指定请求 编辑:程序博客网 时间:2024/06/15 12:36
用栈实现比较简单,遇到数字压栈,遇到运算符号两次出栈运算,再将结果压栈,遍历一次vector即可。
注意:将字符串转为int时,使用atoi可以accept,但用自己编写的转换函数会超时。
//2014年8月20日20:35:12//2014年8月20日21:08:26#include <iostream>#include <stack>#include <vector>#include <string>#include <stdlib.h>using namespace std;class Solution {public: int evalRPN(vector<string> &tokens) { stack<int> st; for(vector<string>::size_type i=0 ; i<tokens.size() ; i++){ if(tokens[i] == "+"){ int b = st.top(); st.pop(); int a = st.top(); st.pop(); st.push(a + b); } else if(tokens[i] == "-"){ int b = st.top(); st.pop(); int a = st.top(); st.pop(); st.push(a - b); } else if(tokens[i] == "*"){ int b = st.top(); st.pop(); int a = st.top(); st.pop(); st.push(a * b); } else if(tokens[i] == "/"){ int b = st.top(); st.pop(); int a = st.top(); st.pop(); st.push(a / b); } else {// int a = myStringToInt(tokens[i]); int a = atoi((tokens[i]).c_str());;// cout << tokens[i] << " " << a << endl; st.push(a); } } return st.top(); } int myStringToInt(string &s) { if(s == ""){ return 0; } int ret = 1; bool IsPositive = false;// cout << s << endl; if(s[0] == '-'){ IsPositive = true; } else{ ret = ret * (int)(s[0] - '0'); } for(string::size_type i=1 ; i<s.length() ; i++){ ret *= 10; ret += (int)(s[i] - '0'); } if(IsPositive == true){ return 0 - ret; } else{ return ret; } }};int main(){ vector<string> tokens;// tokens.push_back("2");// tokens.push_back("1");// tokens.push_back("+");// tokens.push_back("3");// tokens.push_back("*"); tokens.push_back("4"); tokens.push_back("13"); tokens.push_back("5"); tokens.push_back("/"); tokens.push_back("+"); Solution A; cout << A.evalRPN(tokens) << endl; return 0;}
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
- DM642的中断学习
- B - Machine Schedule(二分图匹配——匈牙利算法)
- 根据打开文件句柄查找文件
- Spring 注解学习手札(七) 补遗——@ResponseBody,@RequestBody,@PathVariable
- Task Flow使用指南之七:SavePoints(1)
- 【leetcode】Evaluate Reverse Polish Notation
- c++:vector
- Task Flow使用指南之七:SavePoints(2)
- Task Flow使用指南之七:SavePoints(3)
- 深度卷积神经网络CNNs的多GPU并行框架及其应用
- 底层因为接受到操作系统信号而停止
- JQuery中操作Css样式的方法
- nyoj 题目839 合并
- Task Flow使用指南之八:Transaction(1)