Skip to main content
Back to problems
#604
Easy Algorithms

Design compressed string iterator

Array String Design Iterator
40.4% acceptance
Mar 31, 2026
460
167
Design and implement a data structure for a compressed string iterator. The given compressed string will be in the form of each letter followed by a positive integer representing the number of this letter existing in the original uncompressed string. Implement the StringIterator class: next() Returns the next character if the original string still has uncompressed characters, otherwise returns a white space. hasNext() Returns true if there is any letter needs to be uncompressed in the original string, otherwise returns false.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
struct StringIterator {
  chars: Vec<(char, i64)>,
  idx: usize,
  remaining: i64,
}

impl StringIterator {
  fn new(compressed_string: String) -> Self {
    let bytes = compressed_string.as_bytes();
    let mut chars = Vec::new();
    let mut i = 0;
    while i < bytes.len() {
      let ch = bytes[i] as char;
      i += 1;
      let mut num: i64 = 0;
      while i < bytes.len() && bytes[i].is_ascii_digit() {
        num = num * 10 + (bytes[i] - b'0') as i64;
        i += 1;
      }
      chars.push((ch, num));
    }
    let remaining = if chars.is_empty() { 0 } else { chars[0].1 };
    StringIterator { chars, idx: 0, remaining }
  }

  fn next(&mut self) -> char {
    if !self.has_next() {
      return ' ';
    }
    let ch = self.chars[self.idx].0;
    self.remaining -= 1;
    if self.remaining == 0 {
      self.idx += 1;
      if self.idx < self.chars.len() {
        self.remaining = self.chars[self.idx].1;
      }
    }
    ch
  }

  fn has_next(&self) -> bool {
    self.idx < self.chars.len()
  }
}