17. Letter Combinations of a Phone Number
Last updated
Last updated
/**
* Time complexity :
* Space complexity :
*/
class Solution {
private final char[][] charMap = {{}, {}, {'a', 'b', 'c'},
{'d', 'e', 'f'}, {'g', 'h', 'i'},
{'j', 'k', 'l'}, {'m', 'n', 'o'},
{'p', 'q', 'r', 's'}, {'t', 'u', 'v'},
{'w', 'x', 'y', 'z'}};
public List<String> letterCombinations(String digits) {
List<String> resultList = new ArrayList<>();
if(digits == null || digits.isEmpty()) {
return resultList;
}
letterCombinations(digits, 0, new StringBuilder(), resultList);
return resultList;
}
private void letterCombinations(String digits,
int index,
StringBuilder combSB,
List<String> resultList) {
if(index == digits.length()) {
resultList.add(combSB.toString());
return;
}
int digitIndex = digits.charAt(index)-'0';
for(char ch: charMap[digitIndex]) {
combSB.append(ch);
letterCombinations(digits, index+1, combSB, resultList);
combSB.deleteCharAt(index);
}
}
}