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. SVN (TortioseSVN) 版本控制之忽略路径(如:bin、obj)

    在SVN版本控制时,新手经常会遇到这样的问题: 1.整个项目一起提交时会把bin . gen . .project 一同提交至服务器 2.避免提交编译.本地配置等文件在项目中单独对src.res进行提 ...

  2. test20190903 JKlover

    100+65+100=265,T2就差了一点. 乌合之众 给出一个 n × n 的, 元素为自然数的矩阵.这个矩阵有许许多多个子矩阵, 定义它的所有子矩阵形成的集合为 S . 对于一个矩阵 k , 定 ...

  3. linux下用vim写Python自动缩进的配置

    #首先用 find / -name vimrc 找到vimrc文件#一般在 /etc/vimrc#进入vimrc后加入以下命令 set number set autoindent set shiftw ...

  4. Spring源码窥探之:AOP注解

    AOP也就是我们日常说的@面向切面编程,看概念比较晦涩难懂,难懂的是设计理念,以及这样设计的好处是什么.在Spring的AOP中,常用的几个注解如下:@Aspect,@Before,@After,@A ...

  5. mybatis连接mysql查询时报Cannot convert value '0000-00-00 00:00:00' from column 10 to TIMESTAMP

    今天在学习mybatis框架的时候遇到了一个问题:查询用户表的时候报 Cannot convert value '0000-00-00 00:00:00' from column 10 to TIME ...

  6. go语言的坑

    go语言在for循环中遍历的临时变量地址是一样的 func main() { //SetLogConfToEtcd() for i := 0; i < 5; i++ { a := i fmt.P ...

  7. 将idea中xml文件背景颜色去除(转)

    原贴链接:https://blog.csdn.net/weixin_43215250/article/details/89403678 第一步:除去SQL代码块的背景颜色,步骤如下 设置后还是很影响视 ...

  8. C# where 泛型类型约束

    泛型定义中的 where 子句指定对用作泛型类型.方法.委托或本地函数中类型参数的参数类型的约束. 约束可指定接口.基类或要求泛型类型为引用.值或非托管类型. 它们声明类型参数必须具备的功能. 作为约 ...

  9. 洛谷 P2422 良好的感觉 题解

    P2422 良好的感觉 题目描述 kkk做了一个人体感觉分析器.每一天,人都有一个感受值Ai,Ai越大,表示人感觉越舒适.在一段时间[i, j]内,人的舒适程度定义为[i, j]中最不舒服的那一天的感 ...

  10. 【JZOJ6225】【20190618】计数

    题目 对于一个01串,定义\(f(s)\)为\(f(s) = \sum_{i=0}^{\lfloor \frac{|s|}{2} \rfloor -1 }[s_i=s_{|s|-1-i}]\) 定义\ ...