给一个不包含01的数字字符串,每个数字代表一个字母,请返回其所有可能的字母组合。
下图的手机按键图,就表示了每个数字可以代表的字母。
样例
给定 “23”
返回 [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”]
一刷ac
解题思路:和全排列的思路相同,这里还是用队列存储可能的字母组合,然后查找数组对应的字母,然后更新字母组合。和全排列都要注意的一个细节是初始化队列之后,加入一个空的对象进去,为了从头遍历。
public class Solution {
/**
* @param digits A digital string
* @return all posible letter combinations
*/
public ArrayList<String> letterCombinations(String digits) {
ArrayList<String> res = new ArrayList<String>();
if(digits == null || digits.length() == 0) return res;
HashMap<Character, String> map = new HashMap<Character, String>();
LinkedList<String> queue = new LinkedList<String>();
queue.add("");
map.put('2', "abc");
map.put('3', "def");
map.put('4', "ghi");
map.put('5', "jkl");
map.put('6', "mno");
map.put('7', "pqrs");
map.put('8', "tuv");
map.put('9', "wxyz");
for(int i = 0; i < digits.length(); i++){
String str = map.get(digits.charAt(i));
int size = queue.size();
for(; size > 0; size--){
String s = queue.pollFirst();
for(int j = 0; j < str.length(); j++){
String tmp = s + str.charAt(j);
queue.add(tmp);
}
}
}
res.addAll(queue);
return res;
}
}