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
用Stack。是数字,压入stack,是符号,进行处理。吐两个数n1,n2出来做算术,小心要n2 +-*/ n1,因为stack的原因。
小改进:判断是不是符号可以用 String operators = "+-*/"; if (operators.contains(token)) {} 来写,优雅一点。
class Solution { public int evalRPN(String[] tokens) { if (tokens == null || tokens.length == 0) { return 0; } Stack<Integer> stack = new Stack<>(); for (int i = 0; i < tokens.length; i++) { if (!isOperator(tokens[i])) { stack.push(Integer.parseInt(tokens[i])); } else { int i1 = stack.pop(); int i2 = stack.pop(); if (tokens[i].equals("+")) { stack.push(i2 + i1); } else if (tokens[i].equals("-")) { stack.push(i2 - i1); } else if (tokens[i].equals("*")) { stack.push(i2 * i1); } else if (tokens[i].equals("/")) { stack.push(i2 / i1); } } } return stack.pop(); } private boolean isOperator(String s) { return s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/"); } }