C++ solution 94th percentile


  • 0
    G
    class Solution {
    public:
    
        NestedInteger Deserialize(const string &s, int &I)
        {
            NestedInteger Res;
            
            if(I == s.size() || s[I] == ']')
            {
                I += (I != s.size());
                Res.setInteger(INT_MAX);
                return (Res);
            }
            
            if(s[I] == ',')
            {
                I++;
                return Deserialize(s,I);
            }
            
            if(s[I] == '[')
            {
                I++;
                
                do
                {
                    NestedInteger NI = Deserialize(s,I);
                    
                    if(NI.isInteger() && NI.getInteger() == INT_MAX)
                    {
                       break; 
                    }
                    
                    Res.add(NI);
                    
                }while(1);
            }
            else
            {
                int i = I;
                int Number = 0;
                bool Neg = false;
                
                for(;i < s.size() && (s[i] == '-' || isdigit(s[i])); ++i)
                {
                    if(s[i] == '-')
                    {
                        Neg = true;
                    }
                    else
                    {
                        Number = Number*10 + s[i] -'0';
                    }
                }
                
                Res.setInteger(Number * (Neg ? -1 : 1));
                I = i;
            }
            
            return (Res);
        }
    
        NestedInteger deserialize(string s) 
        {
            int Idx = 0;
            return Deserialize(s,Idx);
        }
    };

Log in to reply
 

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