Skip to content

Commit

Permalink
add letter_combinations
Browse files Browse the repository at this point in the history
  • Loading branch information
phinnl committed May 8, 2024
1 parent 0ecc2b5 commit af8cb47
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
42 changes: 42 additions & 0 deletions src/letter_combinations_of_a_phone_number.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
pub fn letter_combinations(digits: String) -> Vec<String> {
if digits.is_empty() {
return vec![];
}
let mut result = Vec::<String>::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::<Vec<String>>();
for item in digits {
if result.is_empty() {
result = item.chars().map(|c| c.to_string()).collect::<Vec<String>>();
continue;
}
let mut temp_vec: Vec<String> = Vec::<String>::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())
);
}
}
3 changes: 2 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
pub mod jump_game;
pub mod letter_combinations_of_a_phone_number;

0 comments on commit af8cb47

Please sign in to comment.