Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
My first Rust program - Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
// https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
use std::collections::HashMap;
use std::char;
use std::iter::FromIterator;
fn main() {
let mappings = init_map();
find_combinations("23", mappings)
}
fn init_map() -> HashMap<i32, Vec<char>> {
let mut number_to_letters = HashMap::new();
let a_ord = 96; // char 'a'
let mut curr_ord = a_ord;
for n in 0..8 {
let mut letters = Vec::new();
let total = if n + 2 == 7 || n + 2 == 9 { 4 } else { 3 };
for i in 0..total {
letters.push(char::from_u32(curr_ord + i + 1).unwrap());
}
number_to_letters.insert(n + 2, letters);
curr_ord += total;
}
return number_to_letters;
}
fn find_combinations(input: &str, mappings: HashMap<i32, Vec<char>>) {
const RADIX: u32 = 10;
let all_letters: Vec<&Vec<char>> = input
.chars()
.map(|c| c.to_digit(RADIX).unwrap())
.map(|n| mappings.get(&(n as i32)).unwrap())
.collect();
let combinations = permutation(&mut vec![], all_letters);
println!("{:?}", combinations);
}
fn permutation<'a>(curr: &mut Vec<char>, letter_vectors: Vec<&'a Vec<char>>) -> Vec<String> {
if letter_vectors.is_empty() {
return vec![String::from_iter(&*curr)];
}
let mut result = Vec::new();
if let Some((first, rest)) = letter_vectors.split_first() {
for letter in first.iter() {
curr.push(*letter);
result.append(&mut permutation(curr, rest.to_vec()));
curr.pop();
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.