You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.0 KiB

  1. <?php
  2. class Solution
  3. {
  4. const letters = [
  5. 2 => ['a','b','c'],
  6. 3 => ['d','e','f'],
  7. 4 => ['g','h','i'],
  8. 5 => ['j','k','l'],
  9. 6 => ['m','n','o'],
  10. 7 => ['p','q','r','s'],
  11. 8 => ['t','u','v'],
  12. 9 => ['w','x','y','z']
  13. ];
  14. /**
  15. * @param mixed $digits
  16. * @access public
  17. * @return array
  18. */
  19. public static function letterCombinations($digits): array
  20. {
  21. if ($digits === '') {
  22. return [];
  23. }
  24. $lookupResult = [];
  25. $x = 0;
  26. while (count($lookupResult) === 0) {
  27. $lookupResult = self::letters[$digits[$x]] ?? [];
  28. $x++;
  29. }
  30. for ($i = 1; $i < strlen($digits); $i++) {
  31. $temp = [];
  32. foreach (self::letters[$digits[$i]] as $char) {
  33. foreach ($lookupResult as $r) {
  34. $temp[] = $r . $char;
  35. }
  36. }
  37. $lookupResult = $temp;
  38. }
  39. return $lookupResult;
  40. }
  41. }