-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLetterCombinationsofaPhoneNumber.java
More file actions
75 lines (70 loc) · 2.33 KB
/
LetterCombinationsofaPhoneNumber.java
File metadata and controls
75 lines (70 loc) · 2.33 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
69
70
71
72
73
74
75
package leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* @author eko
* @date 2018/10/20 1:36 PM
*
* 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"].
* Note:
*
* Although the above answer is in lexicographical order, your answer could be in any order you want.
*/
public class LetterCombinationsofaPhoneNumber {
public static void main(String[] args) {
String digits = "23";
List<String> res = new LetterCombinationsofaPhoneNumber().letterCombinations(digits);
System.out.println(res);
}
private static List<String> lists = new ArrayList<>();
public List<String> letterCombinations(String digits) {
if (digits == null || digits.length() == 0) {
return new ArrayList<>();
}
lists.add("abc");
lists.add("def");
lists.add("ghi");
lists.add("jkl");
lists.add("mno");
lists.add("pqrs");
lists.add("tuv");
lists.add("wxyz");
List<Integer> indexs = new ArrayList<>();
for (int i = 0; i< digits.length(); i++) {
indexs.add(Integer.valueOf(digits.charAt(i) + ""));
}
List<StringBuilder> sb = new ArrayList<>();
sb.add(new StringBuilder());
List<String> res = createResult(0, indexs, sb);
return res;
}
public List<String> createResult(int i, List<Integer> indexs, List<StringBuilder> builders) {
if (i == indexs.size()) {
List<String> res = new ArrayList<>();
for (StringBuilder sb : builders) {
res.add(sb.toString());
}
return res;
}
List<StringBuilder> next = new ArrayList<>();
for (StringBuilder sb : builders) {
String s = this.lists.get(indexs.get(i)-2);
for (int j = 0; j < s.length(); j++) {
StringBuilder newSb = new StringBuilder(sb);
newSb.append(s.charAt(j));
next.add(newSb);
}
}
i++;
return createResult(i, indexs, next);
}
}