-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy path17-letter-combinations-of-a-phone-number.java
More file actions
68 lines (55 loc) · 2.26 KB
/
17-letter-combinations-of-a-phone-number.java
File metadata and controls
68 lines (55 loc) · 2.26 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.HashMap;
import java.util.List;
import java.util.Map;
class Solution {
// Approach: Backtracking
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
if (digits == null || digits.isEmpty()) {
return result;
}
Map<Character, String> phoneMap = new HashMap<>();
phoneMap.put('2', "abc");
phoneMap.put('3', "def");
phoneMap.put('4', "ghi");
phoneMap.put('5', "jkl");
phoneMap.put('6', "mno");
phoneMap.put('7', "pqrs");
phoneMap.put('8', "tuv");
phoneMap.put('9', "wxyz");
backtrack(digits, 0, phoneMap, new StringBuilder(), result);
return result;
}
private void backtrack(
String digits,
int index,
Map<Character, String> phoneMap,
StringBuilder currentCombination,
List<String> result
) {
if (index == digits.length()) {
result.add(currentCombination.toString());
return;
}
char digit = digits.charAt(index);
String letters = phoneMap.get(digit);
for (char letter : letters.toCharArray()) {
currentCombination.append(letter);
backtrack(digits, index + 1, phoneMap, currentCombination, result);
currentCombination.deleteCharAt(currentCombination.length() - 1); // Backtrack
}
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println("Testing Letter Combinations of a Phone Number:");
String digits1 = "23";
System.out.println("Input: \"23\" -> Output: " + sol.letterCombinations(digits1) + " (Expected: [ad, ae, af, bd, be, bf, cd, ce, cf])");
String digits2 = "";
System.out.println("Input: \"\" -> Output: " + sol.letterCombinations(digits2) + " (Expected: [])");
String digits3 = "2";
System.out.println("Input: \"2\" -> Output: " + sol.letterCombinations(digits3) + " (Expected: [a, b, c])");
String digits4 = "79";
System.out.println("Input: \"79\" -> Output: " + sol.letterCombinations(digits4) + " (Expected: [pw, px, py, pz, qw, qx, qy, qz, rw, rx, ry, rz, sw, sx, sy, sz])");
}
}