-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLettersCombinations.java
More file actions
68 lines (51 loc) · 1.88 KB
/
Copy pathLettersCombinations.java
File metadata and controls
68 lines (51 loc) · 1.88 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
/**
* Letter Combinations of a Phone Number
* https://leetcode.com/problems/letter-combinations-of-a-phone-number/
*/
public class LettersCombinations {
public static void letterCombinationsRec(String digits,
StringBuilder sb,
Map<Character, String> mapLetters,
List<String> outputDigits) {
if (sb.length() == digits.length()) {
outputDigits.add(sb.toString());
return;
}
for (char ch : mapLetters.get(digits.charAt(sb.length())).toCharArray()) {
sb.append(ch);
letterCombinationsRec(digits,
sb,
mapLetters,
outputDigits);
sb.deleteCharAt(sb.length() - 1);
}
}
public static List<String> letterCombinations(String digits) {
List<String> outputDigits = new ArrayList<>();
if (digits == null || digits.isEmpty()) {
return outputDigits;
}
Map<Character, String> mapLetters = new HashMap<Character, String>();
mapLetters.put('2', "abc");
mapLetters.put('3', "def");
mapLetters.put('4', "ghi");
mapLetters.put('5', "jkl");
mapLetters.put('6', "mno");
mapLetters.put('7', "pqrs");
mapLetters.put('8', "tuv");
mapLetters.put('9', "wxyz");
StringBuilder sb = new StringBuilder();
letterCombinationsRec(digits,
sb,
mapLetters,
outputDigits);
return outputDigits;
}
public static void main(String[] args) {
letterCombinations("23");
}
}