-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLetterCombinationFinder.java
46 lines (40 loc) · 1.4 KB
/
LetterCombinationFinder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package org.sean.array;
import java.util.*;
/***
* 17. Letter Combinations of a Phone Number
*/
public class LetterCombinationFinder {
static HashMap<Integer, List<String>> map = new HashMap<>();
static {
map.put(2, Arrays.asList("a", "b", "c"));
map.put(3, Arrays.asList("d", "e", "f"));
map.put(4, Arrays.asList("g", "h", "i"));
map.put(5, Arrays.asList("j", "k", "l"));
map.put(6, Arrays.asList("m", "n", "o"));
map.put(7, Arrays.asList("p", "q", "r", "s"));
map.put(8, Arrays.asList("t", "u", "v"));
map.put(9, Arrays.asList("w", "x", "y", "z"));
}
List<String> getCombinations(String str, int index) {
int digit = Integer.parseInt(str.charAt(index) + "");
if(index == str.length() - 1) {
return map.get(digit);
}else {
return merge(map.get(digit), getCombinations(str, ++index));
}
}
private List<String> merge(List<String> letters, List<String> groups) {
List<String> result = new LinkedList<>();
for (String ch : letters) {
for (String str : groups) {
result.add(ch + str);
}
}
return result;
}
public List<String> letterCombinations(String digits) {
if(digits == null || digits.isEmpty())
return Collections.EMPTY_LIST;
return getCombinations(digits, 0);
}
}