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.

img

1
2
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.


Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class {
public List<String> letterCombinations(String digits) {
LinkedList<String> q = new LinkedList<String>();
if(digits.length()==0) return q;
String[] mapping = new String[] {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
q.add("");
for(int i=0; i<digits.length(); i++) {
int m = digits.charAt(i) - '0';
while(q.peek().length()==i) {
String temp = q.remove();
for(char next:mapping[m].toCharArray()) {
q.add(temp+next);
}
}
}
return q;
}
}