题目: 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", "1
题目:
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
解答:
1 public class Solution { 2 3 private static final Set<String> OPERATORS = 4 new HashSet<>(Arrays.asList("+", "-", "*", "/")); 5 6 public int eval(int x, int y, String operator) { 7 switch(operator) { 8 case "+": 9 return x+y; 10 case "-": 11 return x-y; 12 case "*": 13 return x*y; 14 case "/": 15 return x/y; 16 } 17 } 18 19 public int evalPRN(String[] tokens) { 20 Stack<Integer> stack = new Stack<>(); 21 for(String token : tokens) { 22 if(OPERATORS.contais(token)) { 23 int y = stack.pop(); 24 int x = stack.pop(); 25 stack.push(eval(x, y, token)); 26 } else { 27 stack.push(Integer.parseInt(token)); 28 } 29 } 30 31 return stack.pop(); 32 } 33 }