From 8789bbba49c1484ca52d39cf05096f201bd81545 Mon Sep 17 00:00:00 2001 From: Joe Ardent Date: Thu, 25 Apr 2024 17:49:57 -0700 Subject: [PATCH] runlength encoding using the input container as the output --- string_compression/Cargo.toml | 6 +++ string_compression/src/main.rs | 70 ++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 string_compression/Cargo.toml create mode 100644 string_compression/src/main.rs diff --git a/string_compression/Cargo.toml b/string_compression/Cargo.toml new file mode 100644 index 0000000..d9017b5 --- /dev/null +++ b/string_compression/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "string_compression" +version = "0.1.0" +edition = "2021" + +[dependencies] diff --git a/string_compression/src/main.rs b/string_compression/src/main.rs new file mode 100644 index 0000000..4ee6bee --- /dev/null +++ b/string_compression/src/main.rs @@ -0,0 +1,70 @@ +fn main() { + let mut a = ['a', 'a', 'b', 'b', 'c', 'c', 'c']; + let mut b = ['a', 'a', 'a', 'b', 'b', 'a', 'a']; + let mut c = ['a']; + let mut d = ['a', 'b', 'b', 'b']; + let mut e = ['a', 'b', 'c']; + + let sz = Solution::compress(&mut a); + dbg!(sz, a); + + let sz = Solution::compress(&mut b); + dbg!(sz, b); + + let sz = Solution::compress(&mut c); + dbg!(sz, c); + + let sz = Solution::compress(&mut d); + dbg!(sz, d); + + let sz = Solution::compress(&mut e); + dbg!(sz, e); +} + +struct Solution; + +/* + NOTE: the key to making this work was using a separate "start" marker for the start index of the + current char; I kept trying to use the "write" variable compared with the read var. +*/ + +impl Solution { + pub fn compress(chars: &mut [char]) -> i32 { + let (mut read, mut write) = (1, 0); + let len = chars.len(); + let mut last = chars[0]; + let mut start = 0; + while read < len { + let cur = chars[read]; + if cur != last { + chars[write] = last; + last = cur; + let count = read - start; + start = read; + if count > 1 { + for c in Self::tok(count) { + write += 1; + chars[write] = c; + } + } + write += 1; + } + read += 1; + } + + chars[write] = last; + let count = read - start; + if count > 1 { + for c in Self::tok(count) { + write += 1; + chars[write] = c; + } + } + + write as i32 + 1 + } + + fn tok(num: usize) -> Vec { + num.to_string().chars().collect() + } +}