LeetCode 385: Mini Parser Solution

Master LeetCode problem 385 (Mini Parser), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

385. Mini Parser

Problem Explanation

Explanation

To solve this problem, we can use a recursive approach. We iterate through the input string character by character.

  • If we encounter a digit or a negative sign, we parse the integer and create a new NestedInteger object with that integer.
  • If we encounter an opening bracket '[', we recursively call the same function to parse the nested list inside the brackets.
  • If we encounter a comma ',', we continue to the next element.
  • If we encounter a closing bracket ']', we finish parsing the current NestedInteger.

Time Complexity

The time complexity of this solution is O(n), where n is the length of the input string.

Space Complexity

The space complexity of this solution is O(n) due to the recursive calls.

Solution Code

public NestedInteger deserialize(String s) {
    if (s.isEmpty()) {
        return new NestedInteger();
    }
    if (s.charAt(0) != '[') {
        return new NestedInteger(Integer.parseInt(s));
    }
    
    Stack<NestedInteger> stack = new Stack<>();
    NestedInteger current = null;
    int start = 1;
    
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c == '[') {
            if (current != null) {
                stack.push(current);
            }
            current = new NestedInteger();
            start = i + 1;
        } else if (c == ']' || c == ',') {
            if (i > start) {
                current.add(deserialize(s.substring(start, i)));
            }
            start = i + 1;
            if (c == ']') {
                if (!stack.isEmpty()) {
                    NestedInteger top = stack.pop();
                    top.add(current);
                    current = top;
                }
            }
        }
    }
    
    return current;
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 385 (Mini Parser)?

This page provides optimized solutions for LeetCode problem 385 (Mini Parser) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 385 (Mini Parser)?

The time complexity for LeetCode 385 (Mini Parser) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 385 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 385 in Java, C++, or Python.

Back to LeetCode Solutions