Created
May 30, 2021 01:39
-
-
Save deedee47/fdd55cb4dbc236909ace2f127113d0d7 to your computer and use it in GitHub Desktop.
Returns a list of combined words given a sequence of numbers and a Number-Letter Mapping
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Keypad Number to Letter Mapping | |
//2-9 corresponds to letters on the phone keypad and the same index of the array | |
private static String[] keyPadMapping = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv" ,"wxyz"}; | |
public static List<String> playNumberLetterCombination(String number){ | |
List<String> combinedWords = new ArrayList<>(); | |
//empty or wrong input | |
if(number.isEmpty() || !number.matches("\\d+")) return combinedWords; | |
combination("", number, 0, combinedWords); | |
return combinedWords; | |
} | |
private static void combination(String combo, String number, int numberIndex, List<String> combinedWords) | |
{ | |
//break recursion here | |
if(numberIndex >= number.length()){ | |
combinedWords.add(combo); | |
return; | |
} | |
//get number | |
int index = Character.digit(number.charAt(numberIndex), 10); | |
//get corresponding letters | |
String letters = keyPadMapping[index]; //retrieve number mapping | |
for(int i = 0; i < letters.length(); i++){ | |
combination(combo+letters.charAt(i), number, numberIndex + 1, combinedWords); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello @deedee47, congratulations 🎉 your solution has been selected as one of the winning solutions in Week 8 of #AlgorithmFridays.
Your solution is clean, readable and passed the tests. I like your use of regex on line 10 and recursion for solving this problem - that was neat!
Out of the many winning solutions, only 3 will be selected for the $20 prize in a raffle draw. The raffle draw will hold today, Friday June 4 at 3.00pm WAT (7.00 am PST)
If you are interested in being a part of the raffle draw, please send me a DM on Twitter @meekg33k so I can share the event invite with you.
NB: Only solutions of participants who indicated interest in the raffle draw will be considered.
Thanks once again for participating and see you later today for Week 9 of #AlgorithmFridays.