Skip to content

Commit 23de407

Browse files
committed
Letter Combinations of a Phone Number
1 parent 88a38e0 commit 23de407

File tree

2 files changed

+83
-1
lines changed

2 files changed

+83
-1
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/// @number 17
2+
/// @title Letter Combinations of a Phone Number
3+
/// @url https://leetcode.com/problems/letter-combinations-of-a-phone-number/
4+
/// @difficulty medium
5+
6+
7+
struct Solution;
8+
9+
impl Solution {
10+
pub fn letter_combinations(digits: String) -> Vec<String> {
11+
let len = digits.len();
12+
if len < 1 { return vec![]; };
13+
14+
let x = &digits[len - 1..];
15+
let letter_chars = match x {
16+
"2" => vec!["a", "b", "c"],
17+
"3" => vec!["d", "e", "f"],
18+
"4" => vec!["g", "h", "i"],
19+
"5" => vec!["j", "k", "l"],
20+
"6" => vec!["m", "n", "o"],
21+
"7" => vec!["p", "q", "r", "s"],
22+
"8" => vec!["t", "u", "v"],
23+
"9" => vec!["w", "x", "y", "z"],
24+
_ => vec![]
25+
};
26+
let letter_chars_len = letter_chars.len();
27+
28+
if len == 1 {
29+
return letter_chars.iter().map(|c| String::from(*c)).collect::<Vec<String>>();
30+
}
31+
32+
if letter_chars_len < 1 {
33+
return Solution::letter_combinations(String::from(&digits[..len - 1]));
34+
}
35+
36+
37+
let prefix = Solution::letter_combinations(String::from(&digits[..len - 1]));
38+
39+
let mut ret = vec![];
40+
if prefix.len() > 0 {
41+
for x in prefix {
42+
for y in letter_chars.clone() {
43+
ret.push(format!("{}{}", x.clone(), y.clone()));
44+
}
45+
}
46+
ret
47+
} else {
48+
letter_chars.iter().map(|c| String::from(*c)).collect::<Vec<String>>()
49+
}
50+
}
51+
}
52+
53+
#[cfg(test)]
54+
mod test {
55+
use crate::letter_combinations_of_a_phone_number::Solution;
56+
use std::vec::Vec;
57+
58+
#[test]
59+
fn should_work_with_one_letter() {
60+
assert_eq!(
61+
vec!["a", "b", "c"].iter().map(|c| String::from(*c)).collect::<Vec<String>>(),
62+
Solution::letter_combinations("2".into())
63+
);
64+
}
65+
66+
#[test]
67+
fn should_work_with_two_letter() {
68+
assert_eq!(
69+
vec!["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].iter().map(|c| String::from(*c)).collect::<Vec<String>>(),
70+
Solution::letter_combinations("23".into())
71+
);
72+
}
73+
74+
#[test]
75+
fn should_work_with_two_letter_with_invalid_letter() {
76+
assert_eq!(
77+
vec!["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].iter().map(|c| String::from(*c)).collect::<Vec<String>>(),
78+
Solution::letter_combinations("213".into())
79+
);
80+
}
81+
}

src/main.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,4 +27,5 @@ mod string_to_integer_atoi;
2727
mod palindrome_number;
2828
mod container_with_most_water;
2929
mod three_sum;
30-
mod three_sum_closest;
30+
mod three_sum_closest;
31+
mod letter_combinations_of_a_phone_number;

0 commit comments

Comments
 (0)