forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
LetterPhoneNumber.java
55 lines (49 loc) · 1.73 KB
/
LetterPhoneNumber.java
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
package backtracking;
import java.util.ArrayList;
import java.util.List;
/**
* Created by gouthamvidyapradhan on 09/03/2017.
* Given a digit string, return all possible letter combinations that the number could represent.
* <p>
* A mapping of digit to letters (just like on the telephone buttons) is given below.
* 1 2(abc) 3(def)
* 4(ghi) 5(jkl) 6(mno)
* 7(pqrs) 8(tuv) 9(wxyz)
* <p>
* <p>
* Input:Digit string "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 LetterPhoneNumber {
private String[] NUMBER_ALPHA = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
/**
* Main method
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
List<String> result = new LetterPhoneNumber().letterCombinations("23");
result.forEach(System.out::println);
}
private List<String> letterCombinations(String digits) {
if (digits == null || digits.isEmpty() || digits.contains("1") || digits.contains("0"))
return new ArrayList<>();
List<String> prev = new ArrayList<>();
prev.add("");
for (int i = digits.length() - 1; i >= 0; i--) {
String str = NUMBER_ALPHA[Integer.parseInt(String.valueOf(digits.charAt(i)))];
List<String> newList = new ArrayList<>();
for (int j = 0, l = str.length(); j < l; j++) {
for (String s : prev) {
s = str.charAt(j) + s;
newList.add(s);
}
}
prev = newList;
}
return prev;
}
}