您的位置:首页 > 其它

17. Letter Combinations of a Phone Number

2017-04-13 04:52 435 查看
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"].


public class Solution {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
if(digits == null || digits.length() == 0){
return result;
}
Map<Character, char[]> map = new HashMap<Character, char[]>();
map.put('2', new char[]{'a', 'b', 'c'});
map.put('3', new char[]{'d', 'e', 'f'});
map.put('4', new char[]{'g', 'h', 'i'});
map.put('5', new char[]{'j', 'k', 'l'});
map.put('6', new char[]{'m', 'n', 'o'});
map.put('7', new char[]{'p', 'q', 'r', 's'});
map.put('8', new char[]{'t', 'u', 'v'});
map.put('9', new char[]{'w', 'x', 'y', 'z'});
StringBuilder sb = new StringBuilder();
dfs(digits, sb, map, result);
return result;
}

public void dfs(String digits, StringBuilder sb, Map<Character, char[]> map, List<String> result){
if(sb.length() == digits.length()){
result.add(sb.toString());
return;
}
for(char c : map.get(digits.charAt(sb.length()))){ //利用sb.length()查到当前到了第几位
sb.append(c);
dfs(digits, sb, map, result);
sb.deleteCharAt(sb.length() - 1);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: