leetcode-17-java

问题:17. Letter Combinations of a Phone Number

1
2
3
4
5
6
7
8
9
Given a string containing digits from 2-9 inclusive, 
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. Note that 1 does not map to any letters.
Example:

Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

leetcode地址

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
private static List<String> baseList = new ArrayList<String>(){{
add(null);
add(null);
add("abc");
add("def");
add("ghi");
add("jkl");
add("mno");
add("pqrs");
add("tuv");
add("wxyz");
}};

public static List<String> letterCombinations(String digits) {
List<String> list = new ArrayList<>();
if (null == digits || digits.length() == 0) {
return list;
}


for (int i = 0; i < digits.length(); i++) {
char[] chars = baseList.get(Integer.parseInt(String.valueOf(digits.charAt(i)))).toCharArray();
if (i == 0) {
for (char c : chars) {
list.add(String.valueOf(c));
}
} else {
int len = list.size();
for (int j = 0; j < len; j++) {
for (char c : chars) {
list.add(list.get(j) + c);
}
}
list = list.subList(len, list.size());
}

}
return list;
}