class Solution {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<>();
String[] str = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
for (int i=0; i<digits.length();i++) {
result = combination(result, str[digits.charAt(i)-'0'-2])
}
return result;
}
public List<String> combination(List<String> s1, String s2) {
List<String> str = new ArrayList<>();
for (int i=0; i<s2.length();i++) {
if (s1.isEmpty()) {
str.add(s2.substring(i, i+1));
}else {
for (String s:s1) {
str.add(s+s2.substring(i, i+1));
}
}
}
return str;
}
}
答案解析:
如上代码,先定义好键盘按键 str,然后for循环直到遍历完字符串digits的长度。
其中 str[digits.charAt(i)-'0'-2的目的是,例如digits=“23”,那么digits.charAt(i)-'0'就是将字符值的ASCII码相减,也就是将字符值转换成int类型的值。-2的操作是因为题目中键盘上0,1都没有字母,只有从2开始才会有字母,才有遍历的必要。
然后进入下面的combination函数。如果result(也就是s1)刚开始为空,则直接将s2的值放入str里面,如果不为空,则遍历result(也就是s1),然后和s2进行拼接。