11 lines concise and easy understand c++ solution


  • 11
    A
    class Solution {
    public:
        bool isValidSerialization(string preorder) {
            istringstream iss(preorder);
            int nullcnt = 0, nodecnt = 0;
            string tmp;
            vector<string> vec;
            while(getline(iss, tmp, ',')) vec.push_back(tmp);
            for(int i = 0; i < vec.size(); i++){
                if(vec[i] != "#") nodecnt++;
                else nullcnt++;
                if(nullcnt == nodecnt + 1 && i != vec.size() - 1) return false;
            }
            return nullcnt == nodecnt + 1;
        }
    };

  • 1
    K

    no need to store each element in a vector

    public:
        bool isValidSerialization(string preorder) {
            istringstream s(preorder);
            int node_c = 0, null_c = 0;
            string cur;
            while (getline(s, cur, ',')) {
                if (cur == "#") ++null_c;
                else ++node_c;
                if (s.good() && null_c == node_c + 1) return false;
            }
            return null_c == node_c + 1;
        }
    };

  • 0
    S

    The getline here is fabulous!


  • 0
    A

    Good Job !!!!!!!


Log in to reply
 

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