Last active
February 27, 2019 16:34
-
-
Save LenarBad/33fed19e668b12ec4bfbb73bbff6c112 to your computer and use it in GitHub Desktop.
Interview Question. Generate and print all possible strings that could be created by a phone number, using the letters assigned on the phone Print all possibles strings that could be created by a phone number, using the letters assigned on the phone. Don’t have to store them, just print them
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
private Map<String, List<String>> static final digitToLetterMap = new HashMap() {{ | |
map.put("0", Arrays.asList(" ")); | |
map.put("1", Arrays.asList("")); | |
map.put("2", Arrays.asList("a", "b", "c")); | |
map.put("3", Arrays.asList("d", "e", "f")); | |
map.put("4", Arrays.asList("g", "h", "i")); | |
map.put("5", Arrays.asList("j", "k", "l")); | |
map.put("6", Arrays.asList("m", "m", "o")); | |
map.put("7", Arrays.asList("p", "q", "r", "s")); | |
map.put("8", Arrays.asList("t", "u", "v")); | |
map.put("9", Arrays.asList("w", "x", "y", "z")); | |
}} | |
public void printAllStrings(String number) { | |
Map<String, List<String>> map = getDigitsToLettersMap; | |
allCombinationsForIndex(number, 0); | |
} | |
private void allCombinationForIndex(String number, int index) { | |
for (String ch : digitToLetterMap.get(number.substring(index, index + 1)).getValues()) { | |
if (index == number.length() - 1) { | |
System.out.println(replaceChar(number, index, ch)); | |
} else { | |
allCombinationForIndex(replaceChar(number, index, ch), index + 1); | |
} | |
} | |
private String replaceChar(String string, int index, String ch) { | |
return string.substring(0, index) + ch + string.substring(index + 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.lenar.io/generate-all-strings-from-phone-number/