Skip to main content
Back to problems
#385
Medium Algorithms

Mini parser

String Stack Depth-First Search
42.0% acceptance
Jan 12, 2026
501
1497
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum NestedInteger {
  Int(i32),
  List(Vec<NestedInteger>),
}

impl NestedInteger {
  pub fn serialize(&self) -> String {
    match self {
      NestedInteger::Int(n) => n.to_string(),
      NestedInteger::List(list) => {
        let items: Vec<String> = list.iter().map(|item| item.serialize()).collect();
        format!("[{}]", items.join(","))
      }
    }
  }
}

struct Solution;

impl Solution {
  pub fn deserialize(s: String) -> NestedInteger {
    if !s.starts_with('[') {
      return NestedInteger::Int(s.parse().unwrap());
    }
    
    let mut stack = Vec::new();
    let mut num_str = String::new();
    
    for ch in s.chars() {
      match ch {
        '[' => {
          stack.push(NestedInteger::List(Vec::new()));
        }
        ']' => {
          if !num_str.is_empty() {
            if let NestedInteger::List(list) = stack.last_mut().unwrap() {
              list.push(NestedInteger::Int(num_str.parse().unwrap()));
            }
            num_str.clear();
          }
          
          if stack.len() > 1 {
            let top = stack.pop().unwrap();
            if let NestedInteger::List(list) = stack.last_mut().unwrap() {
              list.push(top);
            }
          }
        }
        ',' => {
          if !num_str.is_empty() {
            if let NestedInteger::List(list) = stack.last_mut().unwrap() {
              list.push(NestedInteger::Int(num_str.parse().unwrap()));
            }
            num_str.clear();
          }
        }
        _ => {
          num_str.push(ch);
        }
      }
    }
    
    stack.pop().unwrap()
  }
}