150. Evaluate Reverse Polish Notation
来源:互联网 发布:修图师需要学什么软件 编辑:程序博客网 时间:2024/05/22 12:49
1、题目描述
给一个逆波兰的数学表达式,也就是二叉树的后序排序,返回表达式的计算值。
2、思路
stack,把数值放到stack里,遇到加减乘除,pop出俩元素计算结果,把结果放到stack里。
3、代码
int evalRPN(vector<string>& tokens) { int n = tokens.size(); stack<int>s; for(int i=0;i<n;i++){ if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/"){ int a = s.top(); s.pop(); int b = s.top(); s.pop(); if(tokens[i]=="+"){ s.push(a+b); } else if(tokens[i]=="-"){ s.push(b-a); } else if(tokens[i]=="*"){ s.push(b*a); } else if(tokens[i]=="/"){ s.push(b/a); } } else{ s.push(atoi(tokens[i].c_str())); } } if(s.empty()) return 0; else return s.top(); }
阅读全文
0 0
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- 读取导入excel表txt文档,并存储到List<E>对象中
- 5、ArrayList详解
- 桶(基数)排序与stack的中缀与后缀的转换(C语言)
- 6、fail-fast机制
- 171222 pwn-CGCTF(pwn150)
- 150. Evaluate Reverse Polish Notation
- 图像特征描述子之BRISK
- 7、Queue
- 啊404!
- 外键
- day07_反射
- Troubleshoot Replica Sets
- 8、Deque
- (08)jQuery事件绑定以及解绑