Skip to content

Commit b6b5cb7

Browse files
committed
Add problem 3163: String Compression III
1 parent dbbfd54 commit b6b5cb7

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2115,6 +2115,7 @@ pub mod problem_3158_find_the_xor_of_numbers_which_appear_twice;
21152115
pub mod problem_3159_find_occurrences_of_an_element_in_an_array;
21162116
pub mod problem_3160_find_the_number_of_distinct_colors_among_the_balls;
21172117
pub mod problem_3162_find_the_number_of_good_pairs_i;
2118+
pub mod problem_3163_string_compression_iii;
21182119
pub mod problem_3164_find_the_number_of_good_pairs_ii;
21192120
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21202121

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn compressed_string(word: String) -> String {
7+
let mut result = String::new();
8+
let mut iter = word.bytes();
9+
10+
'outer: while let Some(mut first) = iter.next() {
11+
let mut count = b'1';
12+
13+
loop {
14+
if let Some(c) = iter.next() {
15+
if c == first {
16+
if count < b'8' {
17+
count += 1;
18+
} else {
19+
result.extend(['9', char::from(first)]);
20+
21+
break;
22+
}
23+
} else {
24+
result.extend([char::from(count), char::from(first)]);
25+
first = c;
26+
count = b'1';
27+
}
28+
} else {
29+
result.extend([char::from(count), char::from(first)]);
30+
31+
break 'outer;
32+
}
33+
}
34+
}
35+
36+
result
37+
}
38+
}
39+
40+
// ------------------------------------------------------ snip ------------------------------------------------------ //
41+
42+
impl super::Solution for Solution {
43+
fn compressed_string(word: String) -> String {
44+
Self::compressed_string(word)
45+
}
46+
}
47+
48+
#[cfg(test)]
49+
mod tests {
50+
#[test]
51+
fn test_solution() {
52+
super::super::tests::run::<super::Solution>();
53+
}
54+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod iterative;
2+
3+
pub trait Solution {
4+
fn compressed_string(word: String) -> String;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [("abcde", "1a1b1c1d1e"), ("aaaaaaaaaaaaaabb", "9a5a2b")];
13+
14+
for (word, expected) in test_cases {
15+
assert_eq!(S::compressed_string(word.to_string()), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)