WhiZTiM

Leetcode-17 - Simple

Jul 7th, 2022 (edited)
32
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.29 KB | None | 0 0
  1. class Solution {
  2.    
  3.     private static final Map<Character, List<Character>> MAPPING = Map.ofEntries(
  4.         Map.entry('1', List.of()),
  5.         Map.entry('2', List.of('a', 'b', 'c')),
  6.         Map.entry('3', List.of('d', 'e', 'f')),
  7.         Map.entry('4', List.of('g', 'h', 'i')),
  8.         Map.entry('5', List.of('j', 'k', 'l')),
  9.         Map.entry('6', List.of('m', 'n', 'o')),
  10.         Map.entry('7', List.of('p', 'q', 'r', 's')),
  11.         Map.entry('8', List.of('t', 'u', 'v')),
  12.         Map.entry('9', List.of('w', 'x', 'y', 'z'))
  13.     );
  14.  
  15.  
  16.     private List<String> result = null;
  17.     private void compute(String digits, int index, StringBuilder stringBuilder) {
  18.         if (index == digits.length()) {
  19.             result.add(stringBuilder.toString());
  20.             return;
  21.         }
  22.  
  23.         MAPPING.get(digits.charAt(index)).forEach(value -> {
  24.             stringBuilder.append(value);
  25.             compute(digits, index + 1, stringBuilder);
  26.             stringBuilder.setLength(stringBuilder.length() - 1);
  27.         });
  28.     }
  29.    
  30.     public List<String> letterCombinations(String digits) {
  31.         if (digits.isEmpty()) {
  32.             return List.of();
  33.         }
  34.         result = new ArrayList<>();
  35.         compute(digits, 0, new StringBuilder());
  36.         return result;
  37.     }
  38.    
  39. }
Add Comment
Please, Sign In to add comment