-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path17. Letter Combinations of a Phone Number
39 lines (34 loc) · 1.33 KB
/
17. Letter Combinations of a Phone Number
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
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
if(digits == null || digits.equals("")){
return result;
}
Map<Character, char[]> map = new HashMap<Character, char[]>();
map.put('0', new char[] {});
map.put('1', new char[] {});
map.put('2', new char[] { 'a', 'b', 'c' });
map.put('3', new char[] { 'd', 'e', 'f' });
map.put('4', new char[] { 'g', 'h', 'i' });
map.put('5', new char[] { 'j', 'k', 'l' });
map.put('6', new char[] { 'm', 'n', 'o' });
map.put('7', new char[] { 'p', 'q', 'r', 's' });
map.put('8', new char[] { 't', 'u', 'v'});
map.put('9', new char[] { 'w', 'x', 'y', 'z' });
StringBuilder sb = new StringBuilder();
helper(map, digits, sb, result);
return result;
}
private void helper(Map<Character, char[]> map, String digits,
StringBuilder sb, List<String> result) {
if (sb.length() == digits.length()) {
result.add(sb.toString());
return;
}
for (char c : map.get(digits.charAt(sb.length()))) {
sb.append(c);
helper(map, digits, sb, result);
sb.deleteCharAt(sb.length() - 1);
}
}
}