Skip to content

Commit 3ef33d3

Browse files
committed
Add problem 3039: Apply Operations to Make String Empty
1 parent 86de325 commit 3ef33d3

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2057,6 +2057,7 @@ pub mod problem_3028_ant_on_the_boundary;
20572057
pub mod problem_3033_modify_the_matrix;
20582058
pub mod problem_3035_maximum_palindromes_after_operations;
20592059
pub mod problem_3038_maximum_number_of_operations_with_the_same_score_i;
2060+
pub mod problem_3039_apply_operations_to_make_string_empty;
20602061

20612062
#[cfg(test)]
20622063
mod test_utilities;
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn last_non_empty_string(s: String) -> String {
7+
let mut states = [(0_u32, 0_u32); 26];
8+
9+
(0..).zip(s.bytes()).for_each(|(i, c)| {
10+
let state = &mut states[usize::from(c) - usize::from(b'a')];
11+
12+
state.0 += 1;
13+
state.1 = i;
14+
});
15+
16+
let max_count = states.iter().fold(0, |max, &(count, _)| max.max(count));
17+
let mut buffer = [(0, 0); 26];
18+
let mut length = 0;
19+
20+
(b'a'..).zip(&states).for_each(|(c, &(count, i))| {
21+
if count == max_count {
22+
buffer[length] = (i, c);
23+
length += 1;
24+
}
25+
});
26+
27+
let buffer = &mut buffer[..length];
28+
29+
buffer.sort_unstable_by_key(|&(i, _)| i);
30+
31+
buffer.iter().map(|&(_, c)| char::from(c)).collect()
32+
}
33+
}
34+
35+
// ------------------------------------------------------ snip ------------------------------------------------------ //
36+
37+
impl super::Solution for Solution {
38+
fn last_non_empty_string(s: String) -> String {
39+
Self::last_non_empty_string(s)
40+
}
41+
}
42+
43+
#[cfg(test)]
44+
mod tests {
45+
#[test]
46+
fn test_solution() {
47+
super::super::tests::run::<super::Solution>();
48+
}
49+
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod greedy;
2+
3+
pub trait Solution {
4+
fn last_non_empty_string(s: 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 = [("aabcbbca", "ba"), ("abcd", "abcd")];
13+
14+
for (s, expected) in test_cases {
15+
assert_eq!(S::last_non_empty_string(s.to_string()), expected);
16+
}
17+
}
18+
}

0 commit comments

Comments
 (0)