Java accepted code : very quick


  • 0
    D

    Stack implementation

    public int operation(int i, int j, String op) {
        switch (op) {
        case "+": return i+j;
        case "-": return i-j;
        case "*": return i*j;
        default: return i/j;
        }
    }
    
    public boolean checkOperator(String st){
        return st.equals("+") || st.equals("-") || st.equals("*")|| st.equals("/");
    }
    
    public int evalRPN(String[] tokens) {
        if(tokens==null || tokens.length==0) return 0;
        Stack<Integer> st = new Stack<Integer>();
        for(String str: tokens) {
            if(checkOperator(str)) {
                int j = st.pop();
                int i = st.pop();
                st.push(operation(i, j, str));
            }else {
                st.push(Integer.parseInt(str));
            }
        }
        return st.peek();
    }

  • 0
    I

    Very Quick? Would you please post your duration (ms),thx!


Log in to reply
 

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