Letter Combinations of a Phone Number
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"].

Analysis
- 用一个queue ans, 开始时放入空string “”
- i=0: x=2, t = "", ans: "a", "b", "c"
- i=1: x=3, t = "a", ans: "b","c","ad","ae","af"
t = "b", ans: "c","ad","ae","af","bd","be","bf"
t = "c", ans: "ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"
Code
public List<String> letterCombinations(String digits) {
LinkedList<String> ans = new LinkedList<String>();
if (digits.length()==0) {return ans;}
String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
ans.add("");
for(int i =0; i<digits.length();i++){
int x = Character.getNumericValue(digits.charAt(i));
while(ans.peek().length()==i){
String t = ans.remove();
for(char s : mapping[x].toCharArray())
ans.add(t+s);
}
}
return ans;
}
Reference
Leetcode