|
| 1 | +import java.util.ArrayList; |
| 2 | +import java.util.Collections; |
| 3 | +import java.util.List; |
| 4 | +import java.util.Map; |
| 5 | +import java.util.Set; |
| 6 | + |
| 7 | +public class LetterCombinationsOfAPhoneNumber { |
| 8 | + private static final Map<Character, Set<Character>> NUMBER_TO_CHARS = Map.ofEntries( |
| 9 | + Map.entry('2', Set.of('a', 'b', 'c')), |
| 10 | + Map.entry('3', Set.of('d', 'e', 'f')), |
| 11 | + Map.entry('4', Set.of('g', 'h', 'i')), |
| 12 | + Map.entry('5', Set.of('j', 'k', 'l')), |
| 13 | + Map.entry('6', Set.of('m', 'n', 'o')), |
| 14 | + Map.entry('7', Set.of('p', 'q', 'r', 's')), |
| 15 | + Map.entry('8', Set.of('t', 'u', 'v')), |
| 16 | + Map.entry('9', Set.of('w', 'x', 'y', 'z')) |
| 17 | + ); |
| 18 | + |
| 19 | + public List<String> letterCombinations(String digits) { |
| 20 | + if (digits.isEmpty()) return Collections.emptyList(); |
| 21 | + final List<String> result = new ArrayList<>(); |
| 22 | + addLetterCombinationsToResult(digits, 0, "", result); |
| 23 | + return result; |
| 24 | + } |
| 25 | + |
| 26 | + private void addLetterCombinationsToResult(String s, int i, String current, List<String> result) { |
| 27 | + if (i == s.length()) { |
| 28 | + result.add(current); |
| 29 | + return; |
| 30 | + } |
| 31 | + for (char character : NUMBER_TO_CHARS.get(s.charAt(i))) { |
| 32 | + addLetterCombinationsToResult(s, i + 1, current + character, result); |
| 33 | + } |
| 34 | + } |
| 35 | +} |
0 commit comments