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"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
class Solution {
public LinkedList<String> letterCombinations(String digits) {
String base[] = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
/*
* 先进先出队列
*/
LinkedList<String> result = new LinkedList();
if(digits.isEmpty()) return result;
result.add("");
for(int i = 0;i < digits.length();i++) {
int x = Character.getNumericValue(digits.charAt(i));
/*
* 如果队列头元素字符串的长度与i相等,那么说明此时还有队列的头元素还是上一次拼接过后的状态
* 此时需要取出来,与后面的一个按键的所有字母按个拼接放入队尾
*/
while(result.peek().length() == i) {
String temp = result.remove();
for(char s :base[x].toCharArray()) {
result.add(temp+s);
}
}
}
return result;
}
}