标签:
题目:
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"].
思路:
没啥思路,上来生做。。。就是permutation。一个bug就是,在check input之后,加一个空string到res里。
1 public List<String> letterCombinations(String digits) { 2 List<String> res = new ArrayList<String>(); 3 if (digits == null || digits.length() == 0) { 4 return res; 5 } 6 //BUG: add empty string first! after dealing with the coner case. 7 res.add(""); 8 9 int len = digits.length(); 10 HashMap<Character, String> key = new HashMap<Character, String>(); 11 key.put(‘1‘,""); 12 key.put(‘2‘,"abc"); 13 key.put(‘3‘,"def"); 14 key.put(‘4‘,"ghi"); 15 key.put(‘5‘,"jkl"); 16 key.put(‘6‘,"mno"); 17 key.put(‘7‘,"pqrs"); 18 key.put(‘8‘,"tuv"); 19 key.put(‘9‘,"wxyz"); 20 21 for (int i = 0; i < len; i++) { 22 char digit = digits.charAt(i); 23 String letter = key.get(digit); 24 ArrayList<String> newRes = new ArrayList<String>(); 25 for (int j = 0; j < letter.length(); j++) { 26 for (String t : res) { 27 String subRes = t + letter.charAt(j); 28 newRes.add(subRes); 29 } 30 } 31 res = newRes; 32 } 33 return res; 34 }
Letter Combinations of a Phone Number
标签:
原文地址:http://www.cnblogs.com/gonuts/p/4475159.html