Evaluate Reverse Polish Notation
发布时间:2020-12-14 21:50:24 所属栏目:大数据 来源:网络整理
导读:题目: 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","/"
题目: Evaluate the value of an arithmetic expression in Reverse Polish Notation. ? 解答: 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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |