LeetcodeJun 24, 2026

Mini Parser

Hazrat Ali

Leetcode

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.

 

Example 1:

Input: s = "324"
Output: 324
Explanation: You should return a NestedInteger object which contains a single integer 324.

Example 2:

Input: s = "[123,[456,[789]]]"
Output: [123,[456,[789]]]
Explanation: Return a NestedInteger object containing a nested list with 2 elements:
1. An integer containing value 123.
2. A nested list containing two elements:
    i.  An integer containing value 456.
    ii. A nested list with one element:
         a. An integer containing value 789

Solution
/**
 * @param {string} s
 * @return {NestedInteger}
 */
var deserialize = function(s) {
    // Single integer
    if (s[0] !== '[') {
        const ni = new NestedInteger();
        ni.setInteger(Number(s));
        return ni;
    }

    const stack = [];
    let num = "";
    let curr = null;

    for (let i = 0; i < s.length; i++) {
        const ch = s[i];

        if (ch === '[') {
            const ni = new NestedInteger();

            if (stack.length > 0) {
                stack[stack.length - 1].add(ni);
            }

            stack.push(ni);
        }
        else if (ch === '-' || (ch >= '0' && ch <= '9')) {
            num += ch;
        }
        else if (ch === ',' || ch === ']') {
            if (num.length > 0) {
                const ni = new NestedInteger();
                ni.setInteger(Number(num));
                stack[stack.length - 1].add(ni);
                num = "";
            }

            if (ch === ']') {
                curr = stack.pop();

                if (stack.length === 0) {
                    return curr;
                }
            }
        }
    }

    return curr;
};
 

Comments