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;
}
}