Skip to content

Instantly share code, notes, and snippets.

@LenarBad
Last active Feb 27, 2019
Embed
What would you like to do?
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

This comment has been minimized.

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