#3167
Medium Algorithms Better compression of string
Hash Table String Sorting Counting
75.3% acceptance
Mar 31, 2026
19
4
You are given a string compressed representing a compressed version of a string. The format is a character followed by its frequency. For example, "a3b1a1c2" is a compressed version of the string "aaabacc".
We seek a better compression with the following conditions:
Each character should appear only once in the compressed version.
The characters should be in alphabetical order.
Return the better compression of compressed.
Note: In the better version of compression, the order of letters may change, which is acceptable.
Solution
Rust
Time O(n²)
Space O(1)
impl Solution {
pub fn better_compression(compressed: String) -> String {
let bytes = compressed.as_bytes();
let mut counts = [0i32; 26];
let mut i = 0;
while i < bytes.len() {
let c = (bytes[i] - b'a') as usize;
i += 1;
let mut num = 0;
while i < bytes.len() && bytes[i].is_ascii_digit() {
num = num * 10 + (bytes[i] - b'0') as i32;
i += 1;
}
counts[c] += num;
}
let mut result = String::new();
for c in 0..26 {
if counts[c] > 0 {
result.push((b'a' + c as u8) as char);
result.push_str(&counts[c].to_string());
}
}
result
}
}