File tree Expand file tree Collapse file tree 3 files changed +61
-0
lines changed
problem_3216_lexicographically_smallest_string_after_a_swap Expand file tree Collapse file tree 3 files changed +61
-0
lines changed Original file line number Diff line number Diff line change @@ -2140,6 +2140,7 @@ pub mod problem_3208_alternating_groups_ii;
21402140pub mod problem_3210_find_the_encrypted_string;
21412141pub mod problem_3211_generate_binary_strings_without_adjacent_zeros;
21422142pub mod problem_3212_count_submatrices_with_equal_frequency_of_x_and_y;
2143+ pub mod problem_3216_lexicographically_smallest_string_after_a_swap;
21432144pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21442145
21452146#[ cfg( test) ]
Original file line number Diff line number Diff line change 1+ pub struct Solution ;
2+
3+ // ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+ use std:: mem;
6+
7+ impl Solution {
8+ pub fn get_smallest_string ( s : String ) -> String {
9+ let mut s = s. into_bytes ( ) ;
10+ let mut iter = s. iter_mut ( ) ;
11+ let mut zero = 0 ;
12+ let mut prev = iter. next ( ) . unwrap_or ( & mut zero) ;
13+
14+ for value in iter {
15+ if * value < * prev && ( * prev ^ * value) & 1 == 0 {
16+ mem:: swap ( prev, value) ;
17+
18+ break ;
19+ }
20+
21+ prev = value;
22+ }
23+
24+ String :: from_utf8 ( s) . unwrap ( )
25+ }
26+ }
27+
28+ // ------------------------------------------------------ snip ------------------------------------------------------ //
29+
30+ impl super :: Solution for Solution {
31+ fn get_smallest_string ( s : String ) -> String {
32+ Self :: get_smallest_string ( s)
33+ }
34+ }
35+
36+ #[ cfg( test) ]
37+ mod tests {
38+ #[ test]
39+ fn test_solution ( ) {
40+ super :: super :: tests:: run :: < super :: Solution > ( ) ;
41+ }
42+ }
Original file line number Diff line number Diff line change 1+ pub mod greedy;
2+
3+ pub trait Solution {
4+ fn get_smallest_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 = [ ( "45320" , "43520" ) , ( "001" , "001" ) ] ;
13+
14+ for ( s, expected) in test_cases {
15+ assert_eq ! ( S :: get_smallest_string( s. to_string( ) ) , expected) ;
16+ }
17+ }
18+ }
You can’t perform that action at this time.
0 commit comments