Skip to content

Instantly share code, notes, and snippets.

@LenarBad
Last active February 27, 2019 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LenarBad/33fed19e668b12ec4bfbb73bbff6c112 to your computer and use it in GitHub Desktop.
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
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);
}
@LenarBad
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment