-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLetter_Combinations_of_a_Phone_Number.java
More file actions
62 lines (55 loc) · 1.88 KB
/
Letter_Combinations_of_a_Phone_Number.java
File metadata and controls
62 lines (55 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
public class Solution {
public ArrayList<String> letterCombinations(String digits) {
ArrayList<String> combos = new ArrayList<String>();
if (digits == null) {
return combos;
}
if (digits.length() == 0) {
combos.add(digits);
return combos;
}
return getCombos(digits, "");
}
private ArrayList<String> getCombos(String digits, String prefix) {
ArrayList<String> combos = new ArrayList<String>();
if ((digits == null) || (digits.length() == 0)) {
return combos;
}
if (digits.length() == 1) {
char digit = digits.charAt(0);
String letterString = getLetterString(digit);
for (int i = 0; i < letterString.length(); i++) {
String combo = new String(prefix);
char ch = letterString.charAt(i);
combo = combo + ch;
combos.add(combo);
}
} else {
char digit = digits.charAt(0);
String newDigits = digits.substring(1);
String letterString = getLetterString(digit);
for (int i = 0; i < letterString.length(); i++) {
String newPrefix = new String(prefix);
char ch = letterString.charAt(i);
newPrefix = newPrefix + ch;
combos.addAll(getCombos(newDigits, newPrefix));
}
}
return combos;
}
private String getLetterString(char digit) {
switch (digit) {
case '0': return " ";
case '1': return "";
case '2': return "abc";
case '3': return "def";
case '4': return "ghi";
case '5': return "jkl";
case '6': return "mno";
case '7': return "pqrs";
case '8': return "tuv";
case '9': return "wxyz";
default: return "";
}
}
}