Skip to main content
Back to problems
#3163
Medium Algorithms

String compression iii

String
67.0% acceptance
Feb 24, 2026
632
54
Given a string word, compress it using the following algorithm: Begin with an empty string comp. While word is not empty, use the following operation: Remove a maximum length prefix of word made of a single character c repeating at most 9 times. Append the length of the prefix followed by c to comp. Return the string comp.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn compressed_string(word: String) -> String {
    let bytes = word.as_bytes();
    let n = bytes.len();
    let mut result = String::new();
    let mut i = 0;
    while i < n {
      let c = bytes[i];
      let mut count = 0u8;
      while i < n && bytes[i] == c && count < 9 {
        count += 1;
        i += 1;
      }
      result.push((b'0' + count) as char);
      result.push(c as char);
    }
    result
  }
}