Simple C++ stack solution


  • 0
    	NestedInteger deserialize(string s)
    	{
    		stack<NestedInteger> st;
    		st.push(NestedInteger());
    		istringstream iss(s);
    		string word;
    		while (getline(iss, word, ','))
    		{
    			int N = word.length();
    			int left = 0, right;
    			while (left < N && word[left] == '[')
    			{
    				st.push(NestedInteger());
    				++left;
    			}
    			for (right = left; right < N && word[right] != ']'; ++right);
    			if (right > left)
    				st.top().add(NestedInteger(stoi(word.substr(left, right - left))));
    			while (right++ < N)
    			{
    				auto curr = st.top();
    				st.pop();
    				st.top().add(curr);
    			}
    		}
    		return st.top().getList()[0];
    	}
    

    One thing need be clear here is that [1] is actually two NestedInteger object, one is a nested list, which contains another one: a number.


Log in to reply
 

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