A quick java solution in few lines of code


  • 0
    S

    Recursively collapse each leaf node (replace "n,#,#" with "#") to check you left with "#" at the end

    public boolean isValidSerialization(String s) {
        if(s.equals("#"))   return true;
        if(s.length()<5 )   return false;
        int before=0, after=0;
    	do{
    		before = s.length();
    		s=s.replaceAll("\\d+,#,#", "#");
    		after = s.length();
    	}while(before!=after);
    	return s.length()==1;
    }

Log in to reply
 

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