4ms JAVA solution, beats 98.75% java submitions, easy to understand


  • 1
    L
    public boolean isValidSerialization(String preorder) {
        int len = preorder.length();
        int count = 0;
        
        for(int i=len-1; i>=0; i--){
    
            char tmp = preorder.charAt(i);
            
            if(tmp == ','){
                continue;
            }else if(tmp == '#'){
                count++;
            }else if(tmp != ',' && tmp != '#' && i!=0 && preorder.charAt(i-1)!=','){
                continue;
            }else{
                if(count<2){
                    return false;
                }else{
                    count--;
                }
            }
        }
        
        if(count ==1){
            return true;
        }else{
            return false;
        }
    }

Log in to reply
 

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