C++ stack solution


  • 0
    J
    class Solution {
    public:
        bool isValidSerialization(string preorder) {
            stack<string> stk;
            int i = 0;
            int j = 0;
            while(j<preorder.size())
            {
                while(j<preorder.size()&&preorder[j]!=',')j++;
                string node = preorder.substr(i,j-i);
                cout << node << endl;
                if(node == "#") 
                {
                    while(!stk.empty() && stk.top()=="#") 
                    {
                        stk.pop(); 
                        if(stk.empty()) return false;
                        stk.pop();
                    }//pop two previous element
                    stk.push(node);
                }
                else
                    stk.push(node);
                j++;//skip ','
                i = j;
            }
            return stk.size()==1 && stk.top()=="#"?true:false;
        }
    };
    

Log in to reply
 

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