Skip to content

Commit 7f3b609

Browse files
committed
Add problem 3216: Lexicographically Smallest String After a Swap
1 parent 5381db8 commit 7f3b609

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2140,6 +2140,7 @@ pub mod problem_3208_alternating_groups_ii;
21402140
pub mod problem_3210_find_the_encrypted_string;
21412141
pub mod problem_3211_generate_binary_strings_without_adjacent_zeros;
21422142
pub mod problem_3212_count_submatrices_with_equal_frequency_of_x_and_y;
2143+
pub mod problem_3216_lexicographically_smallest_string_after_a_swap;
21432144
pub mod problem_3350_adjacent_increasing_subarrays_detection_ii;
21442145

21452146
#[cfg(test)]
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
}
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 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+
}

0 commit comments

Comments
 (0)