Advertisement
naderc

Telephone Words

Oct 21st, 2012
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.HashMap;
  3.  
  4. /*
  5.  * Write a program that takes a telephone number as input and print out all the possible "words"
  6.  * or combinations of letters that can represent the given number.
  7.  *
  8.  * Input:Digit string “23"
  9.  * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
  10.  * Note:
  11.  * Although the above answer is in lexicographical order, your answer could be in any order you want.
  12.  */
  13.  
  14. public class PhoneNumber {
  15.    
  16.     public static void main(String[] args) {
  17.         for (String sb : letterCombinations("1203")) {
  18.             System.out.println(sb);
  19.         }
  20.     }
  21.    
  22.    
  23.     public static ArrayList<String> letterCombinations(String digits) {
  24.         ArrayList<String> result = new ArrayList<String>();
  25.         getLetters(digits, 0, new String(), result, getMap());
  26.         return result;
  27.        
  28.     }
  29.    
  30.    
  31.     private static void getLetters(String digits, int index, String sofar,
  32.                     ArrayList<String> result, HashMap<Character, String> map) {
  33.        
  34.         if (index == digits.length()) {
  35.             result.add(sofar);
  36.         }
  37.         else if (digits.charAt(index) == '1') {
  38.             getLetters(digits, index+1, sofar, result, map);
  39.         }
  40.         else {
  41.             String letters = map.get(digits.charAt(index));
  42.             for (int i = 0; i < letters.length(); i++) {
  43.                 getLetters(digits, index+1, sofar + letters.charAt(i), result, map);
  44.             }
  45.         }
  46.     }
  47.    
  48.    
  49.     private static HashMap<Character, String> getMap() {
  50.         HashMap<Character, String> map = new HashMap<Character, String>();
  51.         map.put('1', "");
  52.         map.put('2', "abc");
  53.         map.put('3', "def");
  54.         map.put('4', "ghi");
  55.         map.put('5', "jkl");
  56.         map.put('6', "mno");
  57.         map.put('7', "pqrs");
  58.         map.put('8', "tuv");
  59.         map.put('9', "wxyz");
  60.         map.put('0', " ");
  61.         return map;
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement