From f411c42c5003c40ca102ec1796ae0e49752d7acb Mon Sep 17 00:00:00 2001 From: EFanZh Date: Fri, 15 Sep 2023 20:47:08 +0800 Subject: [PATCH] Add problem 1844: Replace All Digits with Characters --- src/lib.rs | 1 + .../iterative.rs | 34 +++++++++++++++++++ .../mod.rs | 18 ++++++++++ 3 files changed, 53 insertions(+) create mode 100644 src/problem_1844_replace_all_digits_with_characters/iterative.rs create mode 100644 src/problem_1844_replace_all_digits_with_characters/mod.rs diff --git a/src/lib.rs b/src/lib.rs index 78ff1858..b9a15ef0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1416,6 +1416,7 @@ pub mod problem_1832_check_if_the_sentence_is_pangram; pub mod problem_1833_maximum_ice_cream_bars; pub mod problem_1837_sum_of_digits_in_base_k; pub mod problem_1839_longest_substring_of_all_vowels_in_order; +pub mod problem_1844_replace_all_digits_with_characters; #[cfg(test)] mod test_utilities; diff --git a/src/problem_1844_replace_all_digits_with_characters/iterative.rs b/src/problem_1844_replace_all_digits_with_characters/iterative.rs new file mode 100644 index 00000000..c4451943 --- /dev/null +++ b/src/problem_1844_replace_all_digits_with_characters/iterative.rs @@ -0,0 +1,34 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn replace_digits(s: String) -> String { + let mut s = s.into_bytes(); + let mut i = 0; + + while let Some([left, right]) = s.get_mut(i..i + 2) { + *right = *left + (*right - b'0'); + + i += 2; + } + + String::from_utf8(s).unwrap() + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn replace_digits(s: String) -> String { + Self::replace_digits(s) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_1844_replace_all_digits_with_characters/mod.rs b/src/problem_1844_replace_all_digits_with_characters/mod.rs new file mode 100644 index 00000000..2409f3d8 --- /dev/null +++ b/src/problem_1844_replace_all_digits_with_characters/mod.rs @@ -0,0 +1,18 @@ +pub mod iterative; + +pub trait Solution { + fn replace_digits(s: String) -> String; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [("a1c1e1", "abcdef"), ("a1b2c3d4e", "abbdcfdhe")]; + + for (s, expected) in test_cases { + assert_eq!(S::replace_digits(s.to_string()), expected); + } + } +}