17. Letter Combinations of a Phone Number

来源:互联网 发布:淘宝买兔子 编辑:程序博客网 时间:2024/05/16 02:31

Given a digit string, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below.

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.


Solution 1 Iterative

public static List<String> letterCombinations(String digits) {LinkedList<String> list = new LinkedList<String>();if (digits.length() == 0) {return list;}String[] mapping = new String[] { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };list.add("");for (int i = 0; i < digits.length(); i++) {int size = list.size();int x = Character.getNumericValue(digits.charAt(i));for(int j = 0; j < size; j++){String t = list.remove();for (char s : mapping[x].toCharArray()){list.add(t + s);}}}return list;}

Solution 2 Recursive

//recursivestatic String[] strings = new String[] { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };public static List<String> letterCombinations2(String digits) {List<String> list = new LinkedList<String>();if(digits == null || digits.length() == 0) return list;combine("", digits, 0, list);        return list;    }public static void combine(String prefix, String digits, int index, List<String> list){if(index >= digits.length()){list.add(prefix);return;}String letters = strings[(digits.charAt(index) - '0')];for(int i = 0; i < letters.length(); i++){combine(prefix + letters.charAt(i), digits, index + 1, list);}}




0 0
原创粉丝点击