import java.util.*;
public class PhoneMnemonics {
static ArrayList<String> dictionary = new ArrayList<String>();
/* List all the phone mnemonics for the given digit sequence.
* @param input a digit sequence, like "23432" */
public static ArrayList<String> listMnemonics(String input)
{
ArrayList<String> list = new ArrayList<String>();
String[] dic = { "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N",
"O", "P", "Q", "R", "S", "T", "U",
"V", "W", "X", "Y", "Z", "MAD",
"OCD", "PAN", "PCM", "PCO", "RAM", "SAM", "BE" };
for (String i : dic)
dictionary.add(i);
listMnemonics("", input, list);
return list;
}
/* Helper recursive method to list phone mnemonics. This works by finding
* all possibilities for the first digit, then recursing on the rest of the
* string. For example, if prefix is "AB" and remaining is "2", then the
* mnemonics "ABA", "ABB", and "ABC" would be printed.
*
* @param prefix : the part of the mnemonic that has already been built
* @param remaining : the remaining digits to include in the mnemonic */
private static void listMnemonics(String prefix, String remaining,
ArrayList<String> list)
{
// Base case: when there are no more characters to process,
// just print out the mnemonic that we've already built.
if (remaining.isEmpty()) {
if (!list.contains(prefix) && dictionary.contains(prefix))
list.add(prefix);
return;
}
// Recursive case.
if (remaining.charAt(0) == '1' || remaining.charAt(0) == '0') {
listMnemonics(prefix, remaining.substring(1), list);
}
String digits = digitLetters(remaining.charAt(0));
for (int i = 0; i < digits.length(); i++) {
String newPrefix = prefix + digits.charAt(i);
String newRemaining = remaining.substring(1);
listMnemonics(newPrefix, newRemaining, list);
}
}
/**
* Get the letters appearing on a given key of a standard phone keypad.
* @param ch the character representation of a digit on the phone keypad
* (like '2')
* @return a string containing the letters on the given key, or the empty
* string if the key is not recognized
*/
private static String digitLetters(char ch)
{
switch (ch) {
case '2':
return "ABC";
case '3':
return "DEF";
case '4':
return "GHI";
case '5':
return "JKL";
case '6':
return "MNO";
case '7':
return "PQRS";
case '8':
return "TUV";
case '9':
return "WXYZ";
}
return "";
}
public static void main(String[] args)
{
String str = "123";
ArrayList<String> list = listMnemonics(str);
System.out.println(list);
}
}