I don't know why my solution is so slow, O(n) no recursive any ideas?


  • 0
    D

    This is my code, it takes 256 ms. Beats 2 percent of submissions. I know it's not really efficient, but it seems so bad. I don't get it? Any ideas?

        NestedInteger deserialize(string s) {
            stack<NestedInteger> data;
            NestedInteger cur;
            string digits;
            s = '[' + s;
            s = s + ']';
            for(int i = 1; i< s.size()-1;i++){
                if(s[i]=='['){
                    data.push(cur);
                    cur = NestedInteger();
                }else if(s[i]==']'){//assume it exist
                    if(digits.size()){
                        cur.add( NestedInteger(stoi(digits)) );
                        digits="";
                    }
                    data.top().add(cur);
                    cur = data.top();
                    data.pop();
                }else if(s[i]==','){
                    if(digits.size()){
                        cur.add( NestedInteger(stoi(digits)) );
                        digits = "";
                    }
                }else{//digit
                    digits += s[i];
                }
            }
            if(digits.size())
                cur.add( NestedInteger(stoi(digits)) );
            return cur.getList()[0];
        }

Log in to reply
 

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