shriyanshi24jindal

Letter Combinations of a Phone Number

Mar 30th, 2026
120
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 8.56 KB | None | 0 0
  1. class Solution {
  2. public List<String> letterCombinations(String digits) {
  3. List<String> result = new ArrayList<>();
  4.  
  5. if(digits.length() == 0)
  6. return result;
  7.  
  8. Map<Integer, String> map = new HashMap<>();
  9. map.put(0, "");
  10. map.put(1, "");
  11. map.put(2, "abc");
  12. map.put(3, "def");
  13. map.put(4, "ghi");
  14. map.put(5, "jkl");
  15. map.put(6, "mno");
  16. map.put(7, "pqrs");
  17. map.put(8, "tuv");
  18. map.put(9, "wxyz");
  19.  
  20. String str = "";
  21. findCombination(digits, 0, str, result, map);
  22. return result;
  23. }
  24.  
  25. public void findCombination(String digits, int index, String str, List<String> result, Map<Integer, String> map)
  26. {
  27. if(index == digits.length())
  28. {
  29. result.add(str);
  30. return;
  31. }
  32.  
  33. char digitChar = digits.charAt(index);
  34. int digit = digitChar - '0';
  35. String value = map.get(digit);
  36. for(char ch : value.toCharArray())
  37. {
  38. findCombination(digits, index+1, str + ch, result, map);
  39. }
  40. }
  41. }
  42.  
  43. // digits = "34"
  44. // digitChar = '3' map.get('3')="def"
RAW Paste Data Copied