JAVA Stack Easy to understand


  • 0
    X

    use stack, see # pops, the success is the last one is # and the stack is empty.

    public boolean isValidSerialization(String preorder) {
        Stack<String> stack = new Stack<String>();
        String[] comp = preorder.split(",");
        
        for(int i=0; i<comp.length; i++){
            if(comp[i].equals("#")){
                if(i == comp.length-1){
                    if(stack.isEmpty()) return true;
                    else return false;
                }
                if(stack.isEmpty()) return false;
                stack.pop();
            }else{
                stack.push(comp[i]);
            }
        }
        return false;
    }

Log in to reply
 

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