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"].
Solution:
public class Solution {
public List<String> letterCombinations(String digits) {
List<String> ans = new ArrayList<>();
if(digits.length()==0) return ans;
ans.add("");
for(int i=0; i<digits.length(); i++){
List<String> newAns = new ArrayList<>();
for(String s : ans){
for(String d : getDigit(digits.charAt(i))){
newAns.add(s+d);
}
}
ans = newAns;
}
return ans;
}
public String[] getDigit(char c){
switch(c){
case '2': return new String[]{"a","b","c"};
case '3': return new String[]{"d","e","f"};
case '4': return new String[]{"g","h","i"};
case '5': return new String[]{"j","k","l"};
case '6': return new String[]{"m","n","o"};
case '7': return new String[]{"p","q","r","s"};
case '8': return new String[]{"t","u","v"};
case '9': return new String[]{"w","x","y","z"};
}
return null;
}
}