Evaluate Reverse Polish Notation
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Example
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
Analysis:
Use a stack to save the numbers, once an operator is found, pop two numbers from stack, and push the result back to stack. Note: make sure the order of the operands.
1 public class Solution { 2 public int evalRPN(String[] tokens) { 3 if (tokens == null || tokens.length == 0) return 0; 4 Stack<Integer> stack = new Stack<>(); 5 6 for (String token : tokens) { 7 if (isOperator(token)) { 8 if (stack.size() < 2) return 0; 9 int value1 = stack.pop(); 10 int value2 = stack.pop(); 11 if (token.equals("+")) { 12 stack.push(value1 + value2); 13 } else if (token.equals("-")) { 14 stack.push(value2 - value1); 15 } else if (token.equals("*")) { 16 stack.push(value1 * value2); 17 } else { 18 if (value1 == 0) { 19 return Integer.MAX_VALUE; 20 } 21 stack.push(value2 / value1); 22 } 23 } else { 24 stack.push(Integer.parseInt(token)); 25 } 26 } 27 return stack.pop(); 28 } 29 30 private boolean isOperator(String token) { 31 return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/"); 32 } 33 }

浙公网安备 33010602011771号