class Solution {
public List<String> letterCombinations(String digits) {
List<String> answer = new ArrayList<String>();
Map<Integer, String> numberToString = new HashMap<Integer, String>() {
{
put(2, "abc");
put(3, "def");
put(4, "ghi");
put(5, "jkl");
put(6, "mno");
put(7, "pqrs");
put(8, "tuv");
put(9, "wxyz");
}
};
for (char ch : digits.toCharArray()) {
int number = ch - '0';
answer = addCharacter(numberToString.get(number), answer);
}
return answer;
}
public List<String> addCharacter(String str, List<String> answer) {
List<String> nextAnswer = new ArrayList<String>();
if (answer.isEmpty()) {
return str.chars().mapToObj(ch -> Character.toString(ch)).collect(Collectors.toList());
}
for (int i = 0; i < str.length(); i++) {
String lastString = str.substring(i, i + 1);
for (String substring : answer) {
nextAnswer.add(substring + lastString);
}
}
return nextAnswer;
}
}