题目:
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 {
private String[] map = {
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz"
};
private List<String> result; //存放最终结果
private char[] chars; //存放去除0和1后的字符数组
private char[] current; //存放某一个值
private int end = 0;
private int flag; //当前处理的是第几个字符
public List<String> letterCombinations(String digits) {
result = new LinkedList<>();
if(digits != null && digits.length() > 0) {
chars = digits.toCharArray(); //将字符串转成字符数组
//将字符数组中的0和1去除
while(end < chars.length && chars[end] != '1' && chars[end] != '0') {
end++;
}
flag = end + 1;
while(flag < chars.length) {
if(chars[flag] != '0' && chars[flag] != '1') {
chars[end] = chars[flag];
end++;
}
flag++;
}
//end值为去掉0和1后字符数组的长度
//将数组定义为该长度用来存储一个中间值
current = new char[end];
//将flag清0,进入letterCom()方法,找出所有的组合
flag = 0;
letterCom();
}
return result;
}
private void letterCom() {
if(flag >= end) {
//flag已经移动到chars数组的尾部,一个中间值已经产生,将其放入result中
result.add(String.valueOf(current));
} else {
//通过减'2'确定当前字符数字在map数组中所对应的字符串
int num = chars[flag] - '2';
//挨个取map[num]字符串中的每一个字符
for(int i = 0; i < map[num].length(); i++) {
current[flag] = map[num].charAt(i);
//flag++进入下一个数字
flag++;
//递归调用
letterCom();
//下一层所有可能遍历完之后回到之前的位置
flag--;
}
}
}
}
转自:DERRANTCM博客