[LeetCode] 150. 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
逆波兰表达式,所有操作符置于操作数的后面,因此也被称为后缀表示法。逆波兰记法不需要括号来标识操作符的优先级。
逆波兰记法中,操作符置于操作数的后面。例如表达“三加四”时,写作“3 4 +”,而不是“3 + 4”。如果有多个操作符,操作符置于第二个操作数的后面,所以常规中缀记法的“3 - 4 + 5”在逆波兰记法中写作“3 4 - 5 +”:先3减去4,再加上5。使用逆波兰记法的一个好处是不需要使用括号。例如中缀记法中“3 - 4 * 5”与“(3 - 4)*5”不相同,但后缀记法中前者写做“3 4 5 * -”,无歧义地表示“3 (4 5 *) -”;后者写做“3 4 - 5 *”。
逆波兰表达式的解释器一般是基于堆栈的。解释过程一般是:操作数入栈;遇到操作符时,操作数出栈,求值,将结果入栈;当一遍后,栈顶就是表达式的值。因此逆波兰表达式的求值使用堆栈结构很容易实现,并且能很快求值。
注意:逆波兰记法并不是简单的波兰表达式的反转。因为对于不满足交换律的操作符,它的操作数写法仍然是常规顺序,如,波兰记法“/ 6 3”的逆波兰记法是“6 3 /”而不是“3 6 /”;数字的数位写法也是常规顺序。
解法1: 栈Stack
解法2: 递归
Java:
public class Solution {
public int evalRPN(String[] tokens) {
int a,b;
Stack<Integer> S = new Stack<Integer>();
for (String s : tokens) {
if(s.equals("+")) {
S.add(S.pop()+S.pop());
}
else if(s.equals("/")) {
b = S.pop();
a = S.pop();
S.add(a / b);
}
else if(s.equals("*")) {
S.add(S.pop() * S.pop());
}
else if(s.equals("-")) {
b = S.pop();
a = S.pop();
S.add(a - b);
}
else {
S.add(Integer.parseInt(s));
}
}
return S.pop();
}
}
Java:
public int evalRPN(String[] a) {
Stack<Integer> stack = new Stack<Integer>(); for (int i = 0; i < a.length; i++) {
switch (a[i]) {
case "+":
stack.push(stack.pop() + stack.pop());
break; case "-":
stack.push(-stack.pop() + stack.pop());
break; case "*":
stack.push(stack.pop() * stack.pop());
break; case "/":
int n1 = stack.pop(), n2 = stack.pop();
stack.push(n2 / n1);
break; default:
stack.push(Integer.parseInt(a[i]));
}
} return stack.pop();
}
Python:
# Time: O(n)
# Space: O(n)
import operator class Solution:
# @param tokens, a list of string
# @return an integer
def evalRPN(self, tokens):
numerals, operators = [], {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div}
for token in tokens:
if token not in operators:
numerals.append(int(token))
else:
y, x = numerals.pop(), numerals.pop()
numerals.append(int(operators[token](x * 1.0, y)))
return numerals.pop() if __name__ == "__main__":
print(Solution().evalRPN(["2", "1", "+", "3", "*"]))
print(Solution().evalRPN(["4", "13", "5", "/", "+"]))
print(Solution().evalRPN(["10","6","9","3","+","-11","*","/","*","17","+","5","+"]))
C++:
class Solution {
public:
int evalRPN(vector<string> &tokens) {
if (tokens.size() == 1) return atoi(tokens[0].c_str());
stack<int> s;
for (int i = 0; i < tokens.size(); ++i) {
if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/")
{
s.push(atoi(tokens[i].c_str()));
} else {
int m = s.top();
s.pop();
int n = s.top();
s.pop();
if (tokens[i] == "+") s.push(n + m);
if (tokens[i] == "-") s.push(n - m);
if (tokens[i] == "*") s.push(n * m);
if (tokens[i] == "/") s.push(n / m);
}
}
return s.top();
}
};
C++:
class Solution {
public:
int evalRPN(vector<string>& tokens) {
int op = tokens.size() - 1;
return helper(tokens, op);
}
int helper(vector<string>& tokens, int& op) {
string s = tokens[op];
if (s == "+" || s == "-" || s == "*" || s == "/") {
int v2 = helper(tokens, --op);
int v1 = helper(tokens, --op);
if (s == "+") return v1 + v2;
else if (s == "-") return v1 - v2;
else if (s == "*") return v1 * v2;
else return v1 / v2;
} else {
return stoi(s);
}
}
};
All LeetCode Questions List 题目汇总
[LeetCode] 150. Evaluate Reverse Polish Notation 计算逆波兰表达式的更多相关文章
- [LintCode] Evaluate Reverse Polish Notation 计算逆波兰表达式
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...
- [LeetCode] Evaluate Reverse Polish Notation 计算逆波兰表达式
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...
- Java for LeetCode 150 Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...
- LeetCode150_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 OJ:Evaluate Reverse Polish Notation(逆波兰表示法的计算器)
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...
- leetcode 150. Evaluate Reverse Polish Notation ------ java
Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, ...
- LeetCode——150. Evaluate Reverse Polish Notation
一.题目链接:https://leetcode.com/problems/evaluate-reverse-polish-notation/ 二.题目大意: 给定后缀表达式,求出该表达式的计算结果. ...
- Leetcode#150 Evaluate Reverse Polish Notation
原题地址 基本栈操作. 注意数字有可能是负的. 代码: int toInteger(string &s) { ; ] == '-' ? true : false; : ; i < s.l ...
随机推荐
- Linux 修改文件目录权限
修改文件目录权限 chmod chmod u+x b.txt chmod 777 a.txt 修改文件的所有者和所属组 修改所有者chown beifeng a.txt 修改所属组chgrp b ...
- APP测试之MONKEY安装、使用
1.先下载java的jdk;配置java变量 安装好之后会有两个文件夹一个是jdk 一个是jre(运行)然后配置好java环境变量:JAVA_HOME:C:\Program Files\Java\jd ...
- selenium常用的API(七)判断元素是否可见
web页面不可见的元素虽不在页面上显示,但是存在于DOM树中,这些元素webdriver也能找到. element.is_displayed()方法可以判断元素是否在页面上显示,如果显示返回True, ...
- 手写二叉树-先序构造(泛型)-层序遍历(Java版)
如题 先序构造 数据类型使用了泛型,在后续的更改中,更换数据类型只需要少许的变更代码 层序遍历 利用Node类的level属性 所有属性的权限全为public ,为了方便先这么写吧,建议还是用priv ...
- Optimal Marks SPOJ - OPTM(最小割)
传送门 论文<最小割模型在信息学竞赛中的应用>原题 二进制不同位上互不影响,那么就按位跑网络流 每一位上,确定的点值为1的与S连一条容量为INF的有向边.为0的与T连一条容量为INF的有向 ...
- JavaScript基础03——函数的作用域及变量提升
1.作用域 作用域,变量在函数内部作用的范围/区域.有函数的地方就有作用域. 2.局部作用域和全局作用域 function fn(){ var a = 1; } console.log(a); / ...
- Plist文件编辑工具PlistEdit Pro 1.9.1动态调试分析
0x00:简介 PlistEdit Pro是为macOS平台最优秀的属性列表和JSON编辑器.Mac和iOS开发人员在开发应用程序时必须编辑各种属性列表和JSON文件.PlistEdit Pr ...
- (尚022)Vue案例_初始化显示(十分详细!!!)
项目结构目录 所需资料: comment_page文件夹: ====================================================================== ...
- Windbg命令脚本
命令脚本,就是将完成某个特定任务的相关命令组合在一起,保存在脚本文件里,加载到Windbg里执行,达到我们的目的.你可以理解为脚本就是一种语言,就像c或者汇编,但是他不需要编译器将其编译为可执行文件, ...
- 洛谷 P1281 书的复制 题解
P1281 书的复制 题目背景 大多数人的错误原因:尽可能让前面的人少抄写,如果前几个人可以不写则不写,对应的人输出0 0. 不过,已经修改数据,保证每个人都有活可干. 题目描述 现在要把m本有顺序的 ...