A bit longer Java solution with interface


  • 0
    A
    public class Solution {
        public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack<Integer>();
            
            Map<String,Binaryrithmetic> operations = new HashMap<String,Binaryrithmetic>();
            operations.put("+",new Add());
            operations.put("-",new Sub());
            operations.put("*",new Mul());
            operations.put("/",new Div());
    
            for(String token:tokens){
                if(operations.containsKey(token)){
                    int right = stack.pop();
                    int left = stack.pop();
                    stack.push(operations.get(token).operation(left,right));
                }else{
                    stack.push(Integer.parseInt(token));
                }
            }
            return stack.pop();
        }
    }
    
    interface Binaryrithmetic{
        int operation(int left,int right);
    }
    
    class Add implements Binaryrithmetic{
    
        @Override
        public int operation(int left, int right) {
            return left+right;
        }
    }
    
    class Sub implements Binaryrithmetic{
    
        @Override
        public int operation(int left, int right) {
            return left-right;
        }
    }
    
    class Mul implements Binaryrithmetic{
    
        @Override
        public int operation(int left, int right) {
            return left*right;
        }
    }
    
    class Div implements Binaryrithmetic{
    
        @Override
        public int operation(int left, int right) {
            return left/right;
        }
    }

Log in to reply
 

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