[Leetcode][150]Evaluate Reverse Polish Notation (Java)
题目在这里: https://leetcode.com/problems/evaluate-reverse-polish-notation/
【标签】Stack
【题目分析】思路就不多说了吧,大概就是,遇到数字这样的operand, 就先压到栈里面;遇到 +, -, *, / 的话,就可以进行局部的运算了,把栈顶的两个元素拿出来和operator进行运算,算好了,再压回栈里,留着以后继续运算。
【一点心得】 下面贴的是别人的好代码,特别值得一提的是,用了interface的方法,来模拟lambda表达式的功能,用function来作为parameter。而且也很好的增强了代码的可扩展性。
1 public class Solution { 2 3 /** use interface as work-around for lambda expression */ 4 public interface Operator { 5 int eval(int x, int y); 6 } 7 8 @SuppressWarnings("serial") 9 public static final Map<String, Operator> OperatorMap = 10 new HashMap<String, Solution.Operator>(){{ 11 put("+", new Operator() { 12 public int eval(int x, int y) { return x + y; }}); 13 put("-", new Operator() { 14 public int eval(int x, int y) { return x - y; }}); 15 put("*", new Operator() { 16 public int eval(int x, int y) { return x * y; }}); 17 put("/", new Operator() { 18 public int eval(int x, int y) { return x / y; }}); 19 }}; 20 21 public int evalRPN(String[] tokens) { 22 Stack<Integer> operands = new Stack<Integer>(); 23 for (String token : tokens) { 24 if (OperatorMap.containsKey(token)) { 25 // for operator: calculate operation and then push to stack 26 int op2 = operands.pop(); 27 int op1 = operands.pop(); 28 operands.push(OperatorMap.get(token).eval(op1, op2)); 29 } else { 30 // for operand: push to stack 31 operands.push(Integer.parseInt(token)); 32 } 33 } 34 return operands.pop(); 35 } 36 37 }