20240703 Finished

This commit is contained in:
jackfiled 2024-07-03 11:33:13 +08:00
parent 334a659d35
commit efe3732459
2 changed files with 59 additions and 1 deletions

View File

@ -165,3 +165,4 @@ mod p127_word_ladder;
mod p208_implement_trie_prefix_tree;
mod p211_design_add_and_search_words_data_structure;
mod p212_word_search_ii;
mod p17_letter_combinations_of_a_phone_number;

View File

@ -0,0 +1,57 @@
/**
* [17] Letter Combinations of a Phone Number
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn letter_combinations(digits: String) -> Vec<String> {
let mut result = vec![];
let digits: Vec<usize> = digits.chars()
.map(|c| (c.to_digit(10).unwrap() - 2) as usize)
.collect();
let mut str = Vec::with_capacity(digits.len());
Self::search(&digits, &mut str, &mut result, 0);
result
}
fn search(digits: &Vec<usize>, str: &mut Vec<char>, result: &mut Vec<String>, pos: usize) {
let map = vec![
vec!['a', 'b', 'c'],
vec!['d', 'e', 'f'],
vec!['g', 'h', 'i'],
vec!['j', 'k', 'l'],
vec!['m', 'n', 'o'],
vec!['p', 'q', 'r', 's'],
vec!['t', 'u', 'v'],
vec!['w', 'x', 'y', 'z'],
];
if pos >= digits.len() {
if !str.is_empty() {
result.push(str.iter().collect());
}
return;
}
for &c in &map[digits[pos]] {
str.push(c);
Self::search(digits, str, result, pos + 1);
str.pop();
}
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_17() {}
}