[LeetCode]Letter Combinations of a Phone Number
2014-07-18 12:14
281 查看
题目描述
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"].
给出数字键盘的字母组合。
解题思路
可以不用递归,仅使用3次for循环进行求解,但是需要额外的空间来保存每次循环后的list。代码
/** * 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. * @param digits * @return */ public static List<String> letterCombinations(String digits) { String[] dToChar = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; List<String> list = new ArrayList<String>(); if (digits == null) return null; if (digits.length() == 0){ list.add(""); return list; } for (int i = 0; i < digits.length(); i++) { int d = digits.charAt(i) - '0'; List<String> listCopy = new ArrayList<String>(list);//原list的copy list.clear(); for (int j = 0; j < dToChar[d].length(); j++) { if (i != 0) { List<String> subList = new ArrayList<String>(listCopy); for (int k = 0;k < subList.size();k++) { //添加新的字符到末尾 subList.set(k, subList.get(k) + dToChar[d].charAt(j)); } list.addAll(subList); } else { list.add("" + dToChar[d].charAt(j)); } } listCopy.clear(); } return list; }
相关文章推荐
- [LeetCode] Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- LeetCode | Letter Combinations of a Phone Number
- LeetCode_Letter Combinations of a Phone Number
- LeetCode Online Judge 题目C# 练习 - Letter Combinations of a Phone Number
- LeetCode:Letter Combinations of a Phone Number
- [Leetcode 47] 17 Letter Combinations of a Phone Number
- LeetCode 17: Letter Combinations of a Phone Number
- [leetcode]Letter Combinations of a Phone Number
- [Leetcode] Letter Combinations of a Phone Number
- Leetcode: Letter Combinations of a Phone Number
- LeetCode18:Letter Combinations of a Phone Number
- [LeetCode]Letter Combinations of a Phone Number
- leetcode - Letter Combinations of a Phone Number
- LeetCode Letter Combinations of a Phone Number
- 【leetcode】Letter Combinations of a Phone Number
- LeetCode: Letter Combinations of a Phone Number
- LeetCode-Letter Combinations of a Phone Number
- Leetcode Letter Combinations of a Phone Number
- leetcode:Letter Combinations of a Phone Number(手机号码的字母组合)