In this Leetcode Mini Parser problem solution, you have given a string s represents the serialization of a nested list, implement a parser to deserialize it and return the deserialized NestedInteger. Each element is either an integer or a list whose elements may also be integers or other lists.

Leetcode Mini Parser problem solution


Problem solution in Python.

import ast

class Solution:
    def deserialize(self, s: str) -> NestedInteger:
        data = ast.literal_eval(s)
        def nesty(x):
            if isinstance(x, int):
                return NestedInteger(x)
            n = NestedInteger()
            for sub in x:
                n.add(nesty(sub))
            return n
        return nesty(data)



Problem solution in Java.

public class Solution {
    private int i;
    public NestedInteger deserialize(String s) {
        return dfs(s);
    }
    
    private NestedInteger dfs(String s) {
        boolean negative = false;
        if (s.charAt(i) == '[') {
            NestedInteger r = new NestedInteger();
            i++;
            while (s.charAt(i) != ']') {
                if (s.charAt(i) == ',') {
                    i++;
                } else {
                    r.add(dfs(s));
                }
            }
            i++;
            return r;
        } else {
            if (s.charAt(i) == '-') {
                negative = true;
                i++;
            }
            int num = 0;
            while (i < s.length() && Character.isDigit(s.charAt(i))) {
                num *= 10;
                num += s.charAt(i) - '0';
                i++;
            }
            NestedInteger r = new NestedInteger();
            r.setInteger(negative ? -num : num);
            return r;
        }
    }
}


Problem solution in C++.

class Solution {
public:
    typedef NestedInteger ni;
    NestedInteger deserialize(string s) {
        //stack<char>s;
        if(s[0]!='['){
            ni a(stoi(s));
            return a;
        }
        stack<ni>st;
        string temp = "";
        for(int i = 0;i<s.size();i++){
            if(s[i]=='['){
                ni a;
                st.push(a);
                temp = "";
 
            }
            else if(s[i]==','){
                if(temp!=""){
                    ni &par = st.top();
                    par.add(stoi(temp));
                }
                temp = "";
            }
            else if(s[i]==']'){
                ni par = st.top();
                st.pop();
                if(temp!=""){
                    par.add(stoi(temp));
                    temp = "";
                }
                if(st.size()==0){
                    st.push(par);
                    break;
                }
                ni &grandpar = st.top();
                grandpar.add(par);
            }
            else{
                temp+=s[i];
            }
        }
        return st.top();
    }
};