LeetCode331(2021.3.12)

LC331. 验证二叉树的前序序列化

class Solution {
    public boolean isValidSerialization(String preorder) {
        int i = 0, slots = 1;
        while (i < preorder.length()) {
            if (slots == 0) {
                return false;
            }
            if (preorder.charAt(i) == ',') {
                i++;
            }
            else if (preorder.charAt(i) == '#') {
                slots--;
                i++;
            }
            else {
                while (i < preorder.length() && preorder.charAt(i) != ',') {
                    i++;
                }
                slots++;
            }
        }
        return slots == 0;
    }
}

发表评论