Evaluate Reverse Polish Notation——LeetCode

时间:2022-12-09 13:20:07

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

题目大意:给定一个String数组,数据是一个后缀表达式,求这个表达式的值。

解题思路:用栈来保存操作数即可,遇到数就入栈,遇到操作符就从栈里取出两个元素运算然后入栈即可,最后栈里只剩一个元素就是结果。这个不带括号还容易一点,直接上代码。

  static Map<String, Integer> op = new HashMap<>();

    static {
op.put("+", 1);
op.put("-", 2);
op.put("*", 3);
op.put("/", 4);
} public int evalRPN(String[] tokens) {
if (tokens == null || tokens.length == 0) {
return 0;
}
Stack<Integer> nums = new Stack<>();
for (String s : tokens) {
if (op.get(s) != null) {
int fa = nums.pop();
int fb = nums.pop();
if (op.get(s) == 1) {
nums.push(fb + fa);
} else if (op.get(s) == 2) {
nums.push(fb - fa);
} else if (op.get(s) == 3) {
nums.push(fb * fa);
} else {
nums.push(fb / fa);
}
} else {
nums.push(Integer.valueOf(s));
}
}
return nums.peek();
}