[LeetCode] Evaluate Reverse Polish Notation 计算逆波兰表达式
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;
    }
};
类似题目:
参考资料:
https://leetcode.com/problemset/algorithms/
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] Evaluate Reverse Polish Notation 计算逆波兰表达式的更多相关文章
- [LintCode] Evaluate Reverse Polish Notation 计算逆波兰表达式
		
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...
 - [LeetCode] 150. Evaluate Reverse Polish Notation 计算逆波兰表达式
		
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...
 - LeetCode: 150_Evaluate Reverse Polish Notation | 分析逆波兰式 | Medium
		
题目: Evaluate Reverse Polish Notation Evaluatethe value of an arithmetic expression in Reverse Polish ...
 - LeetCode150_Evaluate Reverse Polish Notation评估逆波兰表达式(栈相关问题)
		
题目: Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are+, ...
 - LeetCode OJ:Evaluate Reverse Polish Notation(逆波兰表示法的计算器)
		
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...
 - [LeetCode] Evaluate Reverse Polish Notation [2]
		
题目 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, ...
 - LeetCode: Evaluate Reverse Polish Notation 解题报告
		
Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish No ...
 - [LeetCode]Evaluate Reverse Polish Notation(逆波兰式的计算)
		
原题链接:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ 题目描述: Evaluate the value of a ...
 - [leetcode]Evaluate Reverse Polish Notation @ Python
		
原题地址:https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ 题意: Evaluate the value of an ...
 
随机推荐
- Linux资源管理-IO优先级
			
前一篇博客介绍了利用 cgroup 来控制进程的 CPU和内存使用情况, 这次补上使用 cgroup 来控制进程的IO优先级的方法. 前提条件 如果想控制进程的IO优先级, 需要内核的支持, 内核编译 ...
 - 一个由Response.Redirect 引起的性能问题的分析
			
现象: 某系统通过单点登录(SSO) 技术验证用户登录.用户在SSO 系统上通过验证后,跳转到某系统的主页上面.而跳转的时间很长,约1分钟以上. 分析步骤: 在问题复现时抓取Hang dump 进行分 ...
 - 在CentOS或RHEL上安装Nux Dextop仓库
			
介绍 Nux Dextop是类似CentOS.RHEL.ScientificLinux的第三方RPM仓库(比如:Ardour,Shutter等等).目前,Nux Dextop对CentOS/RHEL ...
 - C#-#define条件编译
			
本文导读: C#的预处理器指令从来不会转化为可执行代码的命令,但是会影响编译过程的各个方面,常用的预处理器指令有#define.#undef.#if,#elif,#else和#endif等等,下面介绍 ...
 - [Tool] Open Live Writer 插件更新
			
最新插件下载地址:Memento.OLW_V1.0.0.2.7z 零.历史更新记录 2016.11.24 1. 修正 cnblog 语法高亮中的 SQL.Perl 语法高亮异常 下载地址:Mement ...
 - DataNavigatorButtons
			
备注 您可以访问使用该控件的DataNavigator.Buttons属性显示在一个的DataNavigator控制按钮设置.该属性的返回值是一个DataNavigatorButtons对象. 下图说 ...
 - c#使用Split分割换行符  \r\n
			
c# 使用Split分割 换行符,方法如下(其余方法有空再添加): string str = "aa" + "\r\n" + "bb"; ...
 - enote笔记语言(1)
			
what 是什么 why 为什么 when 何时 where 在哪里 whi ...
 - 关闭firefox的plugincheck
			
每次打开firefox都弹出这个SB页面: https://www.mozilla.org/en-US/plugincheck/ 关不掉, 很是烦人. 经过地番google,找到了答案: about: ...
 - Lind.DDD.SSO单点登陆组件的使用(原创)
			
回到目录 一般sso的说明 在Lind.DDD框架里,有对单点登陆的集成,原理就是各个网站去sso网站统一登陆授权,之后在sso网站将登陆的token进行存储,存储方式随你(cache,redis,m ...