My c++ solution


  • 0
    Z
    bool isValidSerialization(string preorder) {
    vector<string> elems;
    stringstream ss(preorder);
    std::string item;
    while (getline(ss, item, ',')) {
    	elems.push_back(item);
    	//cout << item << endl;
    }
    if (elems.size() %2 == 0)
    	return false;
    if (preorder[preorder.length() - 1] != '#') return false;
    bool flag[1000];
    int j = 0;
    for (int i = 0; i < elems.size(); i++)
    {
    	flag[j] = (elems[i] != "#");
    	while (j >= 2)
    	{
    		if (flag[j] == false && flag[j - 1] == false && flag[j - 2] == true)
    		{
    			j -= 2;
    			if (j >= 0)
    			{
    				//if (flag[j] == false)return false;
    				flag[j] = false;
    			}
    		}
    		else
    			break;
    	}
    	j++;
    }
    return j == 1;
    

    }


  • 0
    J
    class Solution { 
    public:
    bool isValidSerialization(string preorder) {
    	int size = preorder.size();
        int finish_size;
        if(preorder=="#")
        {
            finish_size=1;
        }
        else
        {
            finish_size=-1;
        }
        int replace_num=0;
        int replace_no=-1;
        for(int i=0;i<size;i++)
    	{
    		if(preorder[i]!=',' && preorder[i]!='#')
    		{
    			if(replace_num==0)
    			{
    				replace_no=i;
    			}
    			replace_num++;
    		}
    		if(preorder[i]==','||i==size-1)
    		{
    			if(replace_num>1)
    			{
    				preorder.replace(replace_no,replace_num,"0");
    				i=replace_no;
    				size=preorder.size();
    			}
    			replace_num=0;
    			replace_no=-1;
    		}
    	}
        for(int i=0;i<size-4;)
        {
            if(preorder[i]!='#'&&preorder[i+2]=='#'&&preorder[i+4]=='#')
            {
                preorder.replace(i,5,"#");
            }
            i+=2;
    		size=preorder.size();
            if(i>=size-4)
            {
            	if(size==finish_size)
            	{
               		break;
            	}
                i=0;
                finish_size=size;
            }
        }
        if(finish_size==1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    };

Log in to reply
 

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