题目

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

分析

本题考查的是栈的应用,计算后缀表达式的值。

参考数据结构,栈章节。

AC代码

class Solution {
public:
int evalRPN(vector<string>& tokens) {
if (tokens.empty())
return 0; //存储运算数
stack<int> s; //tokens容量
int size = tokens.size();
for (int i = 0; i < size; ++i)
{
if (!isOper(tokens[i]))
{
s.push(strToInt(tokens[i]));
}
else{
char op = tokens[i][0];
switch (op)
{
int op1, op2;
case '+':
op1 = s.top();
s.pop();
op2 = s.top();
s.pop();
s.push(op2 + op1);
break;
case '-':
op1 = s.top();
s.pop();
op2 = s.top();
s.pop();
s.push(op2 - op1);
break;
case '*':
op1 = s.top();
s.pop();
op2 = s.top();
s.pop();
s.push(op2 * op1);
break;
case '/':
op1 = s.top();
s.pop();
op2 = s.top();
s.pop();
s.push(op2 / op1);
break;
default:
break;
}//switch
}//else
}//for
return s.top(); } //判断是否为运算符
bool isOper(string &str)
{
if (str.size() > 1)
return false; if (str[0] == '+' || str[0] == '-' || str[0] == '*' || str[0] == '/')
return true;
return false;
} //将字符串转换为整数
int strToInt(string &str)
{
if (str.empty())
return 0; // 求字符串长度
int size = str.size(); int flag = 1, pos = 0, sum = 0, multi = 1;
if (str[0] == '-')
{
flag = -1;
pos = 1;
} for (int i = size - 1; i >= pos; --i)
{
sum += (str[i] - '0') * multi;
multi *= 10;
} return flag * sum;
}
};

GitHub测试程序源码

最新文章

  1. PHP引用(&amp;)使用详解
  2. atitit 英文与中文与阿拉伯文的简化解决方案.docx
  3. JPA, JNDI, OSGi
  4. mongodb3.x版本用户管理方法
  5. hdu 4010 动态树 @
  6. shell脚本批量处理字符串
  7. cas 登陆超时 解决方案
  8. dump json 显示中文问题
  9. cocos2d-html5基金会
  10. DRP项目总结
  11. JpaManytoMany
  12. 从拥抱开源到回馈开源,灵雀云助力CNCF中国区培训业务
  13. 实战操作——通过wireshark查看任意qq好友IP
  14. Redis学习笔记(1)-安装Oracle VM VirtualBox
  15. Docker容器中找不到vim命令
  16. Linux 查看CPU信息,机器型号,内存等信息
  17. leetcode题解 candy
  18. 时间处理:计算下一天日期,如输入&quot;2004/12/31&quot;(注释2014年12月31日),则输出&quot;2005/1/1&quot;.
  19. sublime text syntaxdef
  20. 面试必备:HashMap源码解析(JDK8)

热门文章

  1. 2017 Multi-University Training Contest - Team 1 KazaQ&#39;s Socks
  2. 转 在shell脚本中使用expect实现scp传输问题
  3. [译]Understanding ECMAScript 6 内容目录
  4. c#中的特性
  5. WebForm随笔
  6. kafka基础二
  7. vue对象和视图
  8. 【详解】JS中的作用域、闭包和回收机制
  9. Linux自带-系统级性能分析工具 — Perf(转)
  10. KVC/KVO 本质