Simple java solution with no data structure


  • 0
    S
    public boolean isValidSerialization(String preorder) {
        while (preorder.length() > 1) {
            int index = preorder.indexOf(",#,#");
            if (index == -1) return false;
            if (index == 0) return false;
            int pre_end = index-1;
            while (pre_end >= 0 && Character.isDigit(preorder.charAt(pre_end))) {
                pre_end--;
            }
            
            preorder = preorder.substring(0, pre_end+1) + "#" + preorder.substring(index+4);
        }
        return preorder.equals("#");
    }

Log in to reply
 

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