|
14 | 14 | // Input:Digit string "23" |
15 | 15 | // Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. |
16 | 16 |
|
17 | | -public class LetterCombinationsOfAPhoneNumber { |
| 17 | +class LetterCombinationsOfAPhoneNumber { |
18 | 18 | public List<String> letterCombinations(String digits) { |
19 | | - LinkedList<String> result = new LinkedList<>(); |
20 | | - String[] mapping = new String[] { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; |
| 19 | + List<String> result = new ArrayList<String>(); |
21 | 20 |
|
22 | 21 | if(digits == null || digits.length() == 0) { |
23 | 22 | return result; |
24 | 23 | } |
25 | 24 |
|
26 | | - result.add(""); |
| 25 | + String[] mapping = { |
| 26 | + "0", |
| 27 | + "1", |
| 28 | + "abc", |
| 29 | + "def", |
| 30 | + "ghi", |
| 31 | + "jkl", |
| 32 | + "mno", |
| 33 | + "pqrs", |
| 34 | + "tuv", |
| 35 | + "wxyz" |
| 36 | + }; |
27 | 37 |
|
28 | | - for(int i = 0; i < digits.length(); i++) { |
29 | | - int current = Character.getNumericValue(digits.charAt(i)); |
30 | | - |
31 | | - while(result.peek().length() == i) { |
32 | | - String s = result.remove(); |
33 | | - |
34 | | - for(char c : mapping[current].toCharArray()) { |
35 | | - result.add(s + c); |
36 | | - } |
37 | | - } |
38 | | - } |
| 38 | + letterCombinationsRecursive(result, digits, "", 0, mapping); |
39 | 39 |
|
40 | 40 | return result; |
41 | 41 | } |
| 42 | + |
| 43 | + public void letterCombinationsRecursive(List<String> result, String digits, String current, int index, String[] mapping) { |
| 44 | + if(index == digits.length()) { |
| 45 | + result.add(current); |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + String letters = mapping[digits.charAt(index) - '0']; |
| 50 | + for(int i = 0; i < letters.length(); i++) { |
| 51 | + letterCombinationsRecursive(result, digits, current + letters.charAt(i), index + 1, mapping); |
| 52 | + } |
| 53 | + } |
42 | 54 | } |
0 commit comments