runlength encoding using the input container as the output
This commit is contained in:
parent
15fd997707
commit
8789bbba49
2 changed files with 76 additions and 0 deletions
6
string_compression/Cargo.toml
Normal file
6
string_compression/Cargo.toml
Normal file
|
@ -0,0 +1,6 @@
|
|||
[package]
|
||||
name = "string_compression"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
70
string_compression/src/main.rs
Normal file
70
string_compression/src/main.rs
Normal file
|
@ -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<char> {
|
||||
num.to_string().chars().collect()
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue