-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLetterCombinationsofaPhoneNumber.java
More file actions
39 lines (33 loc) · 1.17 KB
/
Copy pathLetterCombinationsofaPhoneNumber.java
File metadata and controls
39 lines (33 loc) · 1.17 KB
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
class Solution {
private static Map<Character, String> map = getPhoneMap();
public List<String> letterCombinations(String digits) {
if(digits == null || digits.equals("")) return Collections.emptyList();
List<String> result = new ArrayList<>();
lch(result, "", digits, 0);
return result;
}
private void lch(List<String> result, String sofar, String digits, int n){
if(n == digits.length()) {
result.add(sofar);
return;
}
char d = digits.charAt(n);
if(!map.containsKey(d)) throw new IllegalArgumentException("x");
String chars = map.get(d);
for(int i = 0; i < chars.length(); i++) {
lch(result, sofar+chars.charAt(i), digits, n+1);
}
}
private static Map<Character, String> getPhoneMap() {
Map<Character, String> map = new HashMap<>();
map.put('2', "abc");
map.put('3', "def");
map.put('4', "ghi");
map.put('5', "jkl");
map.put('6', "mno");
map.put('7', "pqrs");
map.put('8', "tuv");
map.put('9', "wxyz");
return map;
}
}