[Java] Accepted code, using Stack and factory pattern.


  • 5
    J

    Any comment is welcome.

    import java.util.Stack;
    public class L2_EvaluateReversePolishNotation {
        public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack<>();
            for(String str: tokens){
                if(str.matches("-?\\d+")){
                    stack.push(Integer.parseInt(str));
                }
                else {
                    Integer secondOperand = stack.pop();
                    Integer firstOperand = stack.pop();
                    Integer result = OperatorFactory.getInstance(str).op(firstOperand,secondOperand);
                    stack.push(result);
                }
            }
            return stack.pop();
        }
    
        public static void main(String[] args) {
            L2_EvaluateReversePolishNotation instance = new L2_EvaluateReversePolishNotation();
            String[] s = {"18"};
            int result = instance.evalRPN(s);
            System.out.println(result);
        }
    }
    
    
    interface Operator{
        int op(int x, int y);
    }
    
    
    class Add implements Operator{
        public int op(int x, int y) {
            return x+y;
        }
    }
    
    class Minus implements Operator{
        @Override
        public int op(int x, int y) {
            return x-y;
        }
    }
    
    class Mutiply implements Operator{
        @Override
        public int op(int x, int y){
            return x*y;
        }
    }
    
    class Divide implements Operator{
        @Override
        public int op(int x, int y) {
            return x/y;
        }
    }
    
    class OperatorFactory{
        public static Operator getInstance(String op) {
            switch (op){
                case "+": return new Add();
                case "-": return new Minus();
                case "*": return new Mutiply();
                case "/": return new Divide();
                default: throw new RuntimeException("this operator "+op+" is not supported.");
            }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.