diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 1c2568a..8a0ec06 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -284,3 +284,5 @@ mod p684_redundant_connection; mod p685_redundant_connection_ii; mod p3211_generate_binary_strings_without_adjacent_zeros; + +mod p3216_lexicographically_smallest_string_after_a_swap; diff --git a/src/problem/p3216_lexicographically_smallest_string_after_a_swap.rs b/src/problem/p3216_lexicographically_smallest_string_after_a_swap.rs new file mode 100644 index 0000000..7034e4c --- /dev/null +++ b/src/problem/p3216_lexicographically_smallest_string_after_a_swap.rs @@ -0,0 +1,46 @@ +/** + * [3216] Lexicographically Smallest String After a Swap + */ +pub struct Solution {} + +// submission codes start here + +impl Solution { + pub fn get_smallest_string(s: String) -> String { + let mut s: Vec = s.chars().map(|x| x.to_digit(10).unwrap()).collect(); + + for i in 0..s.len() - 1 { + if s[i] % 2 != s[i + 1] % 2 { + continue; + } + + if s[i] > s[i + 1] { + let temp = s[i]; + s[i] = s[i + 1]; + s[i + 1] = temp; + break; + } + } + + s.into_iter().map(|x| x.to_string()).collect() + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_3216() { + assert_eq!( + "43520".to_owned(), + Solution::get_smallest_string("45320".to_owned()) + ); + assert_eq!( + "001".to_owned(), + Solution::get_smallest_string("001".to_owned()) + ); + } +}