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.
Solution in Java:
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList<String>();
Map<String, String> mapDigi = new HashMap<String, String>();
mapDigi.put("2", "abc");
mapDigi.put("3", "def");
mapDigi.put("4", "ghi");
mapDigi.put("5", "jkl");
mapDigi.put("6", "mno");
mapDigi.put("7", "pqrs");
mapDigi.put("8", "tuv");
mapDigi.put("9", "wxyz");
for(int i=0; i<digits.length(); i++){
String curDigi = ""+digits.charAt(i);
String curChars = mapDigi.get(curDigi);
if(result.size()==0){
for(int j=0; j<curChars.length(); j++){
result.add(""+curChars.charAt(j));
}
}
else{
int curLength = result.size();
for(int index=0; index<curLength; index++){
String curStr = result.get(0);
for(int j=0; j<curChars.length(); j++){
result.add(curStr+curChars.charAt(j));
}
result.remove(0);
}
}
}
return result;<strong>
}
}</strong>
Note: 注意7和9对应4个字母,所以不能直接按3的倍数计算其对应字母。从arraylist中移除第i个元素,用list.remove(i)。每个循环中对list中每个元素,在末尾分别加上该digit所对应的字母,然后将该元素删除。