leetcode 17 Letter Combinations of a Phone Number
z

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
3
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.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public List<String> letterCombinations(String digits) {
LinkedList<String> answer = new LinkedList<String>();
if (digits.isEmpty()) return answer;
String[] mapping = new String[]{" ", " ", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
answer.add("");
for(int i=0; i<digits.length(); i++){
String s = mapping[Character.getNumericValue(digits.charAt(i))];
while(answer.peek().length() < i+1){
String t = answer.remove();
for(char c: s.toCharArray()){
answer.add(t+c);
}
}
}
return answer;
}
}
  • Using a queue, every time fetch the fisrt queue and find if it’s length equals to the current processing number. if it’s small, adding the distinct characters of the current processing number’s coresponding Letters.