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 {
public ArrayList<String> letterCombinations(String digits) {
HashMap<Integer, char[]> map = new HashMap<Integer, char[]>();
char c = 'a';
for(int i=2;i<=9;i++) {
if(i==9||i==7) {
char[] cs = new char[4];
cs[0] = c++;
cs[1] = c++;
cs[2] = c++;
cs[3] = c++;
map.put(i, cs);
} else {
char[] cs = new char[3];
cs[0] = c++;
cs[1] = c++;
cs[2] = c++;
map.put(i, cs);
}
}
ArrayList<String> ret = new ArrayList<String>();
if(digits==null) {
return ret;
}
ret.add("");
for(int i=0;i<digits.length();i++) {
int d = Integer.parseInt(digits.substring(i, i+1));
char cs[] = map.get(d);
ArrayList<String> tmp = new ArrayList<String>();
for(char e : cs) {
for(String s : ret) {
tmp.add(s + e);
}
}
ret = tmp;
}
return ret;
}
}
public class Solution {
public List<String> letterCombinations(String digits) {
LinkedList<String> ret = new LinkedList<String>();
if (digits == null || digits.isEmpty()) {
return ret;
}
ret.add("");
String map[] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
for (int i = 0; i < digits.length(); i++) {
int count = ret.size();
while (count-- > 0) {
String str = ret.pop();
int num = digits.charAt(i) - '0';
String cs = map[num];
for (char c : cs.toCharArray()) {
ret.add(str + c);
}
}
}
return ret;
}
}
没有评论:
发表评论