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 计算逆波兰表达式的更多相关文章

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

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

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

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

  3. Java for LeetCode 150 Evaluate Reverse Polish Notation

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

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

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

  5. [leetcode]150. Evaluate Reverse Polish Notation逆波兰表示法

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

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

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

  7. leetcode 150. Evaluate Reverse Polish Notation ------ java

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

  8. LeetCode——150. Evaluate Reverse Polish Notation

    一.题目链接:https://leetcode.com/problems/evaluate-reverse-polish-notation/ 二.题目大意: 给定后缀表达式,求出该表达式的计算结果. ...

  9. Leetcode#150 Evaluate Reverse Polish Notation

    原题地址 基本栈操作. 注意数字有可能是负的. 代码: int toInteger(string &s) { ; ] == '-' ? true : false; : ; i < s.l ...

随机推荐

  1. Kali和Metasploitable2的网络配置

    Kali和Metasploitable2的网络配置 2017年06月19日 16:00:00 weixin_34275734 阅读数 389   原文链接:https://blog.csdn.net/ ...

  2. java基础(14)---修饰符

    修饰符:final .static.public.protected.private.default. 一.final(不能修改) 使用final修饰变量定义:该变量一旦被初始化之后就不允许再被修改. ...

  3. pycharm——常用快捷键操作

    编辑类(Editing): Ctrl + Space 基本的代码完成(类.方法.属性)Ctrl + Alt + Space 类名完成Ctrl + Shift + Enter 语句完成Ctrl + P ...

  4. NPM——npm|cnpm如何升级

    前言 手动更新了node.js版本后,想要升级下npm的版本 步骤 其实无论npm还是cnpm升级的命令都是一样的,除了需要指定包名. 升级npm $ npm install -g npm 查看npm ...

  5. django-缓存django-redis

    https://django-redis-chs.readthedocs.io/zh_CN/latest/ 安装 django-redis 最简单的方法就是用 pip : pip install dj ...

  6. Go语言 - 指针 | new | make

    区别于C/C++中的指针,Go语言中的指针不能进行偏移和运算,是安全指针. 要搞明白Go语言中的指针需要先知道3个概念:指针地址.指针类型和指针取值. 概念 任何程序数据载入内存后,在内存都有他们的地 ...

  7. [51Nod 1222] - 最小公倍数计数 (..怎么说 枚举题?)

    题面 求∑k=ab∑i=1k∑j=1i[lcm(i,j)==k]\large\sum_{k=a}^b\sum_{i=1}^k\sum_{j=1}^i[lcm(i,j)==k]k=a∑b​i=1∑k​j ...

  8. LeetCode 935. Knight Dialer

    原题链接在这里:https://leetcode.com/problems/knight-dialer/ 题目: A chess knight can move as indicated in the ...

  9. S1_搭建分布式OpenStack集群_12 界面horizon安装

    一.界面的安装控制节点安装软件包:# yum install openstack-dashboard -y 修改配置文件:# vim /etc/openstack-dashboard/local_se ...

  10. 2019.12.11 java程序中几种常见的异常以及出现此异常的原因

    1.java.lang.NullpointerException(空指针异常) 原因:这个异常经常遇到,异常的原因是程序中有空指针,即程序中调用了未经初始化的对象或者是不存在的对象. 经常出现在创建对 ...