repl.it
@shahinism/

Compress String Rust

Rust

No description

fork
loading
Files
  • main.rs
  • main.4s37gsrti678ik8u.rcgu.o
  • main.main.7rcbfp3g-cgu.0.rcgu.o
  • main.main.7rcbfp3g-cgu.1.rcgu.o
  • main.main.7rcbfp3g-cgu.2.rcgu.o
  • main.main.7rcbfp3g-cgu.3.rcgu.o
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
fn create_part(character: char, count: i32) -> String {
    let count = if count == 1 { "".to_string() } else { count.to_string() };
    format!("{}{}", character, count)
}

pub fn compress<S: AsRef<str>>(text: S) -> String {
    let text = text.as_ref();

    if text == "" {
        return text.to_string()
    }
    let chars: Vec<char> = text.chars().collect();

    let mut result = String::new();
    let mut prev_char = chars[0];
    let mut count = 0;

    for c in chars {
        if c == prev_char {
            count += 1;
        } else {
            result.push_str(create_part(prev_char, count).as_str());
            prev_char = c;
            count = 1;
        }
    }

    result.push_str(create_part(prev_char, count).as_str());
    if text.len() == result.len() {
        String::from(text)
    } else {
        result
    }
}

fn main() {
    assert_eq!(compress(""), "");
    assert_eq!(compress("ABC"), "ABC");
    assert_eq!(compress("AABBCC"), "AABBCC");
    assert_eq!(compress("AAABCCDDDDE"), "A3BC2D4E");
    assert_eq!(compress("BAAACCDDDD"), "BA3C2D4");
    assert_eq!(compress("AAABAACCDDDD"), "A3BA2C2D4");
    assert_eq!(compress(String::from("AAABAACCDDDD")), "A3BA2C2D4");
    println!("Success: testing compress!");
}
Fetching token
?