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.
public class Solution {
String[] strs = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits) {
List<String> res = new ArrayList<String>();
if (digits == null || digits.length() == 0) {
return res;
}
for(char ch: digits.toCharArray()) {
int digit = ch - '0';
if (digit < 2 || digit > 9) {
return res;
}
}
helper(digits, res, new StringBuilder(), 0);
return res;
}
private void helper(String digits, List<String> list, StringBuilder sb, int index) {
if (index == digits.length()) {
list.add(sb.toString());
return;
}
String chs = strs[digits.charAt(index) - '0'];
for (int i = 0; i < chs.length(); i ++) {
sb.append(chs.charAt(i));
helper(digits, list, sb, index + 1);
sb.deleteCharAt(sb.length() - 1);
}
}
}
也可以采用FIFO的思路先进先出,每出来一个,加上下个数字的每一个字母,再存进去。代码如下:
public List<String> letterCombinations(String digits) {
LinkedList<String> ans = new LinkedList<String>();
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;
}