题目:

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

理解这道题首先要理解什么是波兰表达式、什么是逆波兰表达式,这个表达式的意义何在:看参考链接;

参考链接:

Evaluate Reverse Polish Notation:https://www.cnblogs.com/dolphin0520/p/3708587.html

波兰式、逆波兰式与表达式求值:https://blog.csdn.net/linraise/article/details/20459751

思路:

  我们熟悉的带括号的表达式,叫做中缀表达式,符合人们的直观感受。但是对于计算机来说,开销较大。

  波兰表达式(后缀表达式)的意义在于不需要使用括号来决定哪个运算先运行,利用栈的特性来模拟计算,遍历这个逆波兰表达式数组,遇到操作数推进操作数的栈s;遇到操作符,将栈s顶两个操作数a和b取出进行操作符运算,最后将运算结果c放进栈中。

代码实现:

 class Solution {
public:
int evalRPN(vector<string>& tokens)
{
stack<int> sk;
for(int i = ; i<tokens.size();i++)
{
if( tokens[i]=="+" || tokens[i]=="-" || tokens[i]=="*" || tokens[i]=="/" )
{
if(sk.size()<)
return ;
int op1 = sk.top(); sk.pop();
int op2 = sk.top(); sk.pop();
int res = ; if(tokens[i] == "+")
res = op1+op2;
if(tokens[i] == "-")
res = op2-op1;
if(tokens[i] == "*")
res = op1*op2;
if(tokens[i] == "/")
res = op2/op1; sk.push(res);
}
else sk.push(stoi(tokens[i]));
}
return sk.top();
} };

最新文章

  1. HDU 1233 还是畅通工程(最小生成树)
  2. component
  3. win7 :安装SQL2005
  4. struts 标签&lt;s:ierator&gt;的简单使用说明
  5. php请求URL中的参数有空格
  6. 在 wxWidgets 的介绍中看到的一句话
  7. VS2010 安装使用STLPort
  8. 基于swift语言iOS8的蓝牙连接(初步)
  9. Struts2的通配符配置方式
  10. Vector类
  11. Linux - 修改Cent OS系统的的hostname、配置DNS映射
  12. tjoi2018
  13. 关于esp32的ADC采集
  14. BZOJ 1444:[JSOI2009]有趣的游戏
  15. (转)Ubuntu init启动流程分析
  16. sqlserver 隔离级别 - 转
  17. A1050. String Subtraction
  18. extern、static、restrict、volatile 关键字
  19. centos7及服务器端安装python2.7.13, setuptools, pip
  20. 通过Referer设置来防盗链

热门文章

  1. 【JZOJ4848】【GDOI2017模拟11.3】永恒的契约
  2. python 并发之进程
  3. 2019.8.3 [HZOI]NOIP模拟测试12 C. 分组
  4. python的str,unicode对象的encode和decode方法, Python中字符编码的总结和对比bytes和str
  5. 【转载】Combination Sum
  6. dataframe添加元素指定为列表,不同for循环命名空间下的变量重复问题
  7. 流程控制 Day06
  8. 2018-9-30-VisualStudio-使用多个环境进行调试
  9. part10.3-字符驱动访问揭秘
  10. array_map 用法