您的位置:首页 > 其它

[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;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: