Skip to content

Commit ceafaa5

Browse files
committed
resolve aylei#17
1 parent d4f9774 commit ceafaa5

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,4 @@ mod n0013_roman_to_integer;
1414
mod n0014_longest_common_prefix;
1515
mod n0015_3sum;
1616
mod n0016_3sum_closest;
17+
mod n0017_letter_combinations_of_a_phone_number;
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* [17] Letter Combinations of a Phone Number
3+
*
4+
* Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
5+
*
6+
* A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
7+
*
8+
* <img src="http://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png" />
9+
*
10+
* Example:
11+
*
12+
*
13+
* Input: "23"
14+
* Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
15+
*
16+
*
17+
* Note:
18+
*
19+
* Although the above answer is in lexicographical order, your answer could be in any order you want.
20+
*
21+
*/
22+
pub struct Solution {}
23+
24+
// submission codes start here
25+
26+
impl Solution {
27+
pub fn letter_combinations(digits: String) -> Vec<String> {
28+
// '0' and '1' as placeholder to avoid index shifting
29+
let table: Vec<(char, Vec<char>)> = vec![
30+
('0', vec![]),
31+
('1', vec![]), ('2', vec!['a','b','c']), ('3', vec!['d','e','f']),
32+
('4', vec!['g','h','i']), ('5', vec!['j','k','l']), ('6', vec!['m','n','o']),
33+
('7', vec!['p','q','r','s']), ('8', vec!['t','u','v']), ('9', vec!['w','x','y','z'])
34+
];
35+
if digits.len() < 1 { return vec![] }
36+
let mut combs: Vec<String> = vec![String::with_capacity(digits.len())];
37+
for ch in digits.chars().into_iter() {
38+
let chs = &table[ch.to_digit(10).unwrap() as usize].1;
39+
let mut added: Vec<String> = Vec::with_capacity((chs.len() - 1) * combs.len());
40+
for comb in combs.iter_mut() {
41+
for (i, &alphabetic) in chs.iter().enumerate() {
42+
if i == chs.len() - 1 {
43+
comb.push(alphabetic);
44+
} else {
45+
let mut new_comb = (*comb).clone();
46+
new_comb.push(alphabetic);
47+
added.push(new_comb);
48+
}
49+
}
50+
}
51+
combs.append(&mut added);
52+
}
53+
combs
54+
}
55+
}
56+
57+
// submission codes end
58+
59+
#[cfg(test)]
60+
mod tests {
61+
use super::*;
62+
63+
#[test]
64+
fn test_17() {
65+
assert_eq!(Solution::letter_combinations("23".to_string()), ["cf", "af", "bf", "cd", "ce", "ad", "ae", "bd", "be"]);
66+
}
67+
}

0 commit comments

Comments
 (0)