Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 21.3k
Expand file tree
/
Copy pathLetterCombinationsOfPhoneNumber.java
More file actions
Latest commit
65 lines (54 loc) · 2.41 KB
/
Copy pathLetterCombinationsOfPhoneNumber.java
File metadata and controls
65 lines (54 loc) · 2.41 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
packagecom.thealgorithms.strings;
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.List;
publicfinalclassLetterCombinationsOfPhoneNumber {
privatestaticfinalcharEMPTY = '\0';
// Mapping of numbers to corresponding letters on a phone keypad
privatestaticfinalString[] KEYPAD = newString[] {" ", String.valueOf(EMPTY), "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
privateLetterCombinationsOfPhoneNumber() {
}
/**
* Generates a list of all possible letter combinations that the provided
* array of numbers could represent on a phone keypad.
*
* @param numbers an array of integers representing the phone numbers
* @return a list of possible letter combinations
*/
publicstaticList<String> getCombinations(int[] numbers) {
if (numbers == null) {
returnList.of("");
}
returngenerateCombinations(numbers, 0, newStringBuilder());
}
/**
* Recursive method to generate combinations of letters from the phone keypad.
*
* @param numbers the input array of phone numbers
* @param index the current index in the numbers array being processed
* @param current a StringBuilder holding the current combination of letters
* @return a list of letter combinations formed from the given numbers
*/
privatestaticList<String> generateCombinations(int[] numbers, intindex, StringBuildercurrent) {
// Base case: if we've processed all numbers, return the current combination
if (index == numbers.length) {
returnnewArrayList<>(Collections.singletonList(current.toString()));
}
finalvarnumber = numbers[index];
if (number < 0 || number > 9) {
thrownewIllegalArgumentException("Input numbers must in the range [0, 9]");
}
List<String> combinations = newArrayList<>();
// Iterate over each letter and recurse to generate further combinations
for (charletter : KEYPAD[number].toCharArray()) {
if (letter != EMPTY) {
current.append(letter);
}
combinations.addAll(generateCombinations(numbers, index + 1, current));
if (letter != EMPTY) {
current.deleteCharAt(current.length() - 1); // Backtrack by removing the last appended letter
}
}
returncombinations;
}
}