逆波兰表达式:
逆波兰表达式是一种后缀表达式,所谓后缀就是指算符写在后面。
- 平常使用的算式则是一种中缀表达式,如 ( 1 + 2 ) * ( 3 + 4 ) 。
- 该算式的逆波兰表达式写法为 ( ( 1 2 + ) ( 3 4 + ) * ) 。
逆波兰表达式主要有以下两个优点:
- 去掉括号后表达式无歧义,上式即便写成 1 2 + 3 4 + * 也可以依据次序计算出正确结果。
- 适合用栈操作运算:遇到数字则入栈;遇到算符则取出栈顶两个数字进行计算,并将结果压入栈中
package com.company.myQueue;
import java.util.Stack;
public class Solution5 {
/**
* 输入:tokens = ["4","13","5","/","+"]
* 输出:6
* 解释:该算式转化为常见的中缀算术表达式为:(4 + (13 / 5)) = 6
*/
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<>();
int n = tokens.length;
for (int i = 0; i < n; i++) {
if (stack.size() < 2) {
stack.push(tokens[i]);
} else {
if (tokens[i].equals("+")) {
int x = Integer.parseInt(stack.pop());
int y = Integer.parseInt(stack.pop());
stack.push(String.valueOf(x + y));
} else if (tokens[i].equals("-")) {
int x = Integer.parseInt(stack.pop());
int y = Integer.parseInt(stack.pop());
stack.push(String.valueOf(y - x));
} else if (tokens[i].equals("*")) {
int x = Integer.parseInt(stack.pop());
int y = Integer.parseInt(stack.pop());
stack.push(String.valueOf(y * x));
} else if (tokens[i].equals("/")) {
int x = Integer.parseInt(stack.pop());
int y = Integer.parseInt(stack.pop());
stack.push(String.valueOf(y / x));
} else {
stack.push(tokens[i]);
}
}
}
return Integer.parseInt(stack.pop());
}
}
力扣https://leetcode-cn.com/problems/evaluate-reverse-polish-notation/solution/dong-hua-yan-shi-150-ni-bo-lan-biao-da-s-try7/