Skip to main content

443. String Compression

https://leetcode.com/problems/string-compression/

  • CTCI 1.6 String Compression

Python

Python Itertools Groupby

from itertools import groupby


class Solution:
def compress(self, chars: List[str]) -> int:
stack = []
for key, group in groupby(chars):
count = len(list(group))
stack.append(key)
if count > 1: stack.extend(list(str(count)))
chars[:] = stack

Rust

use std::iter::FromIterator;


impl Solution {
pub fn compress(chars: &mut Vec<char>) -> i32 {
let mut stack: Vec<char> = Vec::new();
let mut i = 0;

while i < chars.len() {
let mut count = 1;
while i + 1 < chars.len() && chars[i] == chars[i + 1] {
i += 1;
count += 1;
}

stack.push(chars[i]);

if count > 1 {
let count_chars: Vec<char> = count.to_string().chars().collect();
stack.extend(count_chars);
}

i += 1;
}

*chars = stack;
chars.len() as i32
}
}