首页 > 其他 > 详细

Evaluate Reverse Polish Notation

时间:2019-02-24 16:10:08      阅读:158      评论:0      收藏:0      [点我收藏+]

题目:

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 }

技术分享图片

 

Evaluate Reverse Polish Notation

原文:https://www.cnblogs.com/wylwyl/p/10426364.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!