017.Letter Combinations of a Phone Number

Solution 1: accepted 4ms

Pretty massy, need to be improved.

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
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
String[] map = {"", "", "abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
for (int i = 0; i < digits.length(); i++) {
char digit = digits.charAt(i);
if (digit == '0' || digit == '1')
return new ArrayList<>();
result = appendAll(result, map[digit - '0']);
}
return result;
}
public List<String> appendAll(List<String> result, String chars) {
List<String> update = new ArrayList<>();
Iterator<String> it = result.iterator();
if (result.size() == 0) {
for (int i = 0; i < chars.length(); i++) {
update.add(chars.charAt(i) + "");
}
} else {
while(it.hasNext()) {
String current = it.next();
for (int i = 0; i < chars.length(); i++) {
update.add(current + chars.charAt(i));
}
}
}
return update;
}