Straight forward C++ solution using stack


  • 0
    K
    class Solution {
    public:
        NestedInteger deserialize(string s) {
            if(count(s.begin(),s.end(),'[')==0) return NestedInteger(atoi(s.c_str()));
            stack<NestedInteger> stk;
            string str="";
            char c;
            stringstream ss(s);
            while(ss>>c)
            {
                if(c=='[')
                    stk.push(NestedInteger());
                else if(c==',')
                {
                    if(!str.empty())
                    {
                        stk.top().add(NestedInteger(atoi(str.c_str())));
                        str="";
                    }
                }
                else if(c==']')
                {
                    if(!str.empty())
                    {
                        stk.top().add(NestedInteger(atoi(str.c_str())));
                        str="";
                    }
                    if(stk.size()>1)
                    {
                        auto temp=stk.top();
                        stk.pop();
                        stk.top().add(temp);
                    }
                }
                else
                    str+=c;
            }
            return stk.top();
        }
    };

Log in to reply
 

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