Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Note:

  • Division between two integers should truncate toward zero.
  • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.

Example 1:

Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Example 2:

Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

Example 3:

Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22

逆波兰表达式就是把操作数放前面,把操作符后置的一种写法,我们通过观察可以发现,第一个出现的运算符,其前面必有两个数字,当这个运算符和之前两个数字完成运算后从原数组中删去,把得到一个新的数字插入到原来的位置,继续做相同运算,直至整个数组变为一个数字。于是按这种思路写了代码如下,但是拿到OJ上测试,发现会有Time Limit Exceeded的错误,无奈只好上网搜答案,发现大家都是用栈做的。仔细想想,这道题果然应该是栈的完美应用啊,从前往后遍历数组,遇到数字则压入栈中,遇到符号,则把栈顶的两个数字拿出来运算,把结果再压入栈中,直到遍历完整个数组,栈顶数字即为最终答案。代码如下:

解法一:

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

我们也可以用递归来做,由于一个有效的逆波兰表达式的末尾必定是操作符,所以我们可以从末尾开始处理,如果遇到操作符,向前两个位置调用递归函数,找出前面两个数字,然后进行操作将结果返回,如果遇到的是数字直接返回即可,参见代码如下:

解法二:

class Solution {
public:
int evalRPN(vector<string>& tokens) {
int op = (int)tokens.size() - ;
return helper(tokens, op);
}
int helper(vector<string>& tokens, int& op) {
string str = tokens[op];
if (str != "+" && str != "-" && str != "*" && str != "/") return stoi(str);
int num1 = helper(tokens, --op);
int num2 = helper(tokens, --op);
if (str == "+") return num2 + num1;
if (str == "-") return num2 - num1;
if (str == "*") return num2 * num1;
return num2 / num1;
}
};

类似题目:

Basic Calculator

Expression Add Operators

参考资料:

https://leetcode.com/problemset/algorithms/

https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/47642/a-recursive-solution-in-cpp

https://leetcode.com/problems/evaluate-reverse-polish-notation/discuss/47544/Challenge-me-neat-C%2B%2B-solution-could-be-simpler

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Evaluate Reverse Polish Notation 计算逆波兰表达式的更多相关文章

  1. [LintCode] Evaluate Reverse Polish Notation 计算逆波兰表达式

    Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...

  2. [LeetCode] 150. Evaluate Reverse Polish Notation 计算逆波兰表达式

    Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...

  3. LeetCode: 150_Evaluate Reverse Polish Notation | 分析逆波兰式 | Medium

    题目: Evaluate Reverse Polish Notation Evaluatethe value of an arithmetic expression in Reverse Polish ...

  4. LeetCode150_Evaluate Reverse Polish Notation评估逆波兰表达式(栈相关问题)

    题目: Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are+, ...

  5. LeetCode OJ:Evaluate Reverse Polish Notation(逆波兰表示法的计算器)

    Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...

  6. [LeetCode] Evaluate Reverse Polish Notation [2]

    题目 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, ...

  7. LeetCode: Evaluate Reverse Polish Notation 解题报告

    Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish No ...

  8. [LeetCode]Evaluate Reverse Polish Notation(逆波兰式的计算)

    原题链接:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ 题目描述: Evaluate the value of a ...

  9. [leetcode]Evaluate Reverse Polish Notation @ Python

    原题地址:https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ 题意: Evaluate the value of an ...

随机推荐

  1. 使用h5的history改善ajax列表请求体验

    信息比较丰富的网站通常会以分页显示,在点“下一页”时,很多网站都采用了动态请求的方式,避免页面刷新.虽然大家都是ajax,但是从一些小的细节还是 可以区分优劣.一个小的细节是能否支持浏览器“后退”和“ ...

  2. LCM性质 + 组合数 - HDU 5407 CRB and Candies

    CRB and Candies Problem's Link Mean: 给定一个数n,求LCM(C(n,0),C(n,1),C(n,2)...C(n,n))的值,(n<=1e6). analy ...

  3. Unicode转义(\uXXXX)的编码和解码

    在涉及Web前端开发时, 有时会遇到\uXXXX格式表示的字符, 其中XXXX是16进制数字的字符串表示形式, 在js中这个叫Unicode转义字符, 和\n \r同属于转义字符. 在其他语言中也有类 ...

  4. ImageSharp .NET Core跨平台图形处理库

    ImageSharp 是支持.NET Core跨平台图形处理库,ImageSharp是ImageProcessor 的.NET Core跨平台实现. ImageSharp 支持如下操作: 调整大小,裁 ...

  5. php N 维数组的读取、设置、删除

    <?php // 例子 $rowList = array(); $rowList[] = array('A'=>'A_1','B'=>'A_1_1','C'=>'A_1_1_1 ...

  6. Xshell显示中文乱码问题

    [文件]–>[打开]–>在打开的session中选择连接的那个,点击[属性] -> [终端], 编码选择为:Unicode(UTF-8),然后重新连接服务器即可.也可以在Xshell ...

  7. hibernate -- HQL语句总结

    1. 查询整个映射对象所有字段 //直接from查询出来的是一个映射对象,即:查询整个映射对象所有字段 String hql = "from Users"; Query query ...

  8. VS2010中dumpbin工具的使用

    用VS2010生成的.obj文件..lib库..dll库..exe执行文件,如果想查看其中这些文件或库包含了哪些函数以及相关的信息(符号清单),可以通过VS2010自带的dumpbin工具来完成. d ...

  9. 在centos 服务器上安装phalcon框架 undefined symbol: php_pdo_get_dbh_ce

    去git 下载对应版本的框架 命令行: sudo yum install php-devel pcre-devel gcc make 然后使用GIT clone到服务器上,然后 git clone g ...

  10. jQuery.ajax(url,[settings])

    概述 通过 HTTP 请求加载远程数据. jQuery 底层 AJAX 实现.简单易用的高层实现见 $.get, $.post 等.$.ajax() 返回其创建的 XMLHttpRequest 对象. ...