原题地址
由于数字长度不定.确实一开始会容易想到用递归来做.但是我自己不喜欢写递归的方法.觉得写起来有难度.所以就直接用队列来写了.
核心思路:以输入"23"为例.将"23"转为"3a" “3b” “3c” 放入队列里.然后再逐个取出.判断的条件就是第一个字符是不是数字,是的话就转换.如果不是的话就证明已经转换完毕,退出循环.
public static List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<>();
if (digits.equals("")) return res;
res.add(digits);
while (res.get(0).charAt(0) - '9' <= 0) {
String temp = res.get(0);
res.remove(0);
String map = fun(temp.charAt(0));
for (int i = 0; i < map.length(); i++)
res.add(temp.substring(1) + map.charAt(i));
}
return res;
}
public static String fun(char x){
switch (x){
case '2':return "abc";
case '3':return "def";
case '4':return "ghi";
case '5':return "jkl";
case '6':return "mno";
case '7':return "pqrs";
case '8':return "tuv";
case '9':return "wxyz";
default:return "";
}
}
(也可以用数组来代替switch,字典也可以.我以为使用switch会快一点,所以就使用了switch,不过反而变慢了.)