Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.HashMap;
- /*
- * Write a program that takes a telephone number as input and print out all the possible "words"
- * or combinations of letters that can represent the given number.
- *
- * Input:Digit string “23"
- * Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
- * Note:
- * Although the above answer is in lexicographical order, your answer could be in any order you want.
- */
- public class PhoneNumber {
- public static void main(String[] args) {
- for (String sb : letterCombinations("1203")) {
- System.out.println(sb);
- }
- }
- public static ArrayList<String> letterCombinations(String digits) {
- ArrayList<String> result = new ArrayList<String>();
- getLetters(digits, 0, new String(), result, getMap());
- return result;
- }
- private static void getLetters(String digits, int index, String sofar,
- ArrayList<String> result, HashMap<Character, String> map) {
- if (index == digits.length()) {
- result.add(sofar);
- }
- else if (digits.charAt(index) == '1') {
- getLetters(digits, index+1, sofar, result, map);
- }
- else {
- String letters = map.get(digits.charAt(index));
- for (int i = 0; i < letters.length(); i++) {
- getLetters(digits, index+1, sofar + letters.charAt(i), result, map);
- }
- }
- }
- private static HashMap<Character, String> getMap() {
- HashMap<Character, String> map = new HashMap<Character, String>();
- map.put('1', "");
- map.put('2', "abc");
- map.put('3', "def");
- map.put('4', "ghi");
- map.put('5', "jkl");
- map.put('6', "mno");
- map.put('7', "pqrs");
- map.put('8', "tuv");
- map.put('9', "wxyz");
- map.put('0', " ");
- return map;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement