JAVA accept O(n) solution, easy to understand


  • 0
    O
    public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack<Integer>();
            stack.push(Integer.parseInt(tokens[0]));
            for(int i = 1; i < tokens.length; i++){
                if(checkOperand(tokens[i])){
                    int num = stack.pop();
                    switch(tokens[i]){
                        case "+":
                            if(!stack.isEmpty()) {
                                stack.push(stack.pop()+num);
                            }
                            break;
                        case "-":
                            if(!stack.isEmpty()){
                                stack.push(stack.pop()-num);
                            }
                            break;
                        case "*":
                            if (!stack.isEmpty()) {
                                stack.push(stack.pop()*num);
                            }
                            break;
                        case "/":
                            if(!stack.isEmpty()){
                                stack.push(stack.pop()/num);
                            }
                            break;
                    }
                }else{
                    stack.push(Integer.parseInt(tokens[i]));
                }
    
            }
            return stack.pop();
        }
    

Log in to reply
 

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