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: For each letter, take its list of corresponding characters, and append to each sub-list of strings in a double for-loop. Watch out for boundary conditions where the subList is empty or where the list of corresponding characters is empty.
public class Solution {
private static final Map<Character, List<Character>> digitToLettersMap = new HashMap<>();
static {
digitToLettersMap.put('0', Collections.emptyList());
digitToLettersMap.put('1', Collections.emptyList());
digitToLettersMap.put('2', Arrays.asList('a', 'b', 'c'));
digitToLettersMap.put('3', Arrays.asList('d', 'e', 'f'));
digitToLettersMap.put('4', Arrays.asList('g', 'h', 'i'));
digitToLettersMap.put('5', Arrays.asList('j', 'k', 'l'));
digitToLettersMap.put('6', Arrays.asList('m', 'n', 'o'));
digitToLettersMap.put('7', Arrays.asList('p', 'q', 'r', 's'));
digitToLettersMap.put('8', Arrays.asList('t', 'u', 'v'));
digitToLettersMap.put('9', Arrays.asList('w', 'x', 'y', 'z'));
}
public List<String> letterCombinations(String digits) {
if (digits.isEmpty()) return Collections.emptyList();
// Recurse on next substring.
List<String> subList = letterCombinations(digits.substring(1));
// Get the list of characters corresponding to the current digit.
List<Character> chars = digitToLettersMap.get(digits.charAt(0));
// If current list is empty, skip and return subList.
if (chars.isEmpty()) return subList;
List<String> answer = new ArrayList<>();
if (subList.isEmpty()) {
// If the subList is empty, just ignore it and return current
// list of characters as a list of strings.
for (char c: chars) {
answer.add(Character.toString(c));
}
} else {
StringBuilder sb = new StringBuilder();
for (char c: chars) {
sb.append(c);
for (String s: subList) {
answer.add(sb.append(s).toString());
sb.setLength(1);
}
sb.setLength(0);
}
}
return answer;
}
}
No comments:
Post a Comment