-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLetterCombinationsOfAPhoneNumberSolution.java
More file actions
38 lines (34 loc) · 1.25 KB
/
LetterCombinationsOfAPhoneNumberSolution.java
File metadata and controls
38 lines (34 loc) · 1.25 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
/**
* Given a digit string, return all possible letter combinations that the number could represent.
*
* A mapping of digit to letters (just like on the telephone buttons) is given below.
*
* Input:Digit string "23"
* Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
*/
public class LetterCombinationsOfAPhoneNumberSolution {
public List<String> letterCombinations(String digits) {
String[] mapping = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
List<String> result = new ArrayList<>();
if (digits != null && digits.length() > 0) {
result.add("");
for (int i = 0; i < digits.length(); i++) {
int num = Integer.parseInt(String.valueOf(digits.charAt(i)));
result = combine(mapping[num].toCharArray(), result);
if (i == digits.length() - 1) {
break;
}
}
}
return result;
}
public List<String> combine(char[] chars, List<String> origin) {
List<String> result = new ArrayList<>();
for (String str : origin) {
for (char c : chars) {
result.add(str + c);
}
}
return result;
}
}