From af8cb474607b71e80c54618545154f4280b6c663 Mon Sep 17 00:00:00 2001 From: phinnl Date: Wed, 8 May 2024 15:32:11 +0700 Subject: [PATCH] add letter_combinations --- src/letter_combinations_of_a_phone_number.rs | 42 ++++++++++++++++++++ src/lib.rs | 3 +- 2 files changed, 44 insertions(+), 1 deletion(-) create mode 100644 src/letter_combinations_of_a_phone_number.rs diff --git a/src/letter_combinations_of_a_phone_number.rs b/src/letter_combinations_of_a_phone_number.rs new file mode 100644 index 0000000..1e9fcb7 --- /dev/null +++ b/src/letter_combinations_of_a_phone_number.rs @@ -0,0 +1,42 @@ +pub fn letter_combinations(digits: String) -> Vec { + if digits.is_empty() { + return vec![]; + } + let mut result = Vec::::new(); + let map = ["abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]; + let digits = digits + .as_bytes() + .iter() + .map(|&item| { + let index = (item as char).to_digit(10).unwrap() - 2; + map[index as usize].to_owned() + }) + .collect::>(); + for item in digits { + if result.is_empty() { + result = item.chars().map(|c| c.to_string()).collect::>(); + continue; + } + let mut temp_vec: Vec = Vec::::new(); + for cur in result { + for char in item.chars() { + temp_vec.push(format!("{cur}{char}")); + } + } + result = temp_vec; + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn example_1() { + assert_eq!( + vec!["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"], + letter_combinations("23".to_owned()) + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index cba4a55..f467c7a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -19,4 +19,5 @@ pub mod repeated_character; pub mod best_time_to_buy_and_sell_stock; pub mod maximum_different_between_increasing_elements; pub mod count_submatrices_with_all_ones; -pub mod jump_game; \ No newline at end of file +pub mod jump_game; +pub mod letter_combinations_of_a_phone_number; \ No newline at end of file