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
Solution in Java
private static final Map<String, List<String>> 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) {
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);
}