File tree Expand file tree Collapse file tree 3 files changed +68
-0
lines changed
problem_3039_apply_operations_to_make_string_empty Expand file tree Collapse file tree 3 files changed +68
-0
lines changed Original file line number Diff line number Diff line change @@ -2057,6 +2057,7 @@ pub mod problem_3028_ant_on_the_boundary;
2057
2057
pub mod problem_3033_modify_the_matrix;
2058
2058
pub mod problem_3035_maximum_palindromes_after_operations;
2059
2059
pub mod problem_3038_maximum_number_of_operations_with_the_same_score_i;
2060
+ pub mod problem_3039_apply_operations_to_make_string_empty;
2060
2061
2061
2062
#[ cfg( test) ]
2062
2063
mod test_utilities;
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments