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"].
This is a classic recursion problem.
Solution:
- Use an array to store mapping of digits to Strings as seen in the telephone keypad. The mapping would be {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}
- If the input String is a digit (2 <= digit <= 9), then we would add each character in the mapped String to the output and return the letter combinations (e.g the letter combinations of 2 are {"a", "b", "c"}
- If there is more than 1 digit in the input, then we would apply the following steps
- Get mapped String "digitLetters" for first character
- Get letter combinations for remaining substring (starting from the 2nd character in input)
- For each letter combination in the combinations for the remaining substring
- For each character c in digitLetters, concatenate c and letter combination
- Add the resulting new letter combination to the output list
public class Solution { String[] digitMap = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; public List<String> letterCombinations(String digits) { List<String> letterCombo = new ArrayList<String>(); if (digits.length() == 0) { return letterCombo; } String digitLetters = digitMap[digits.charAt(0) - '0']; if (digits.length() == 1) { for (int i = 0; i < digitLetters.length(); i++) { letterCombo.add(String.valueOf(digitLetters.charAt(i))); } return letterCombo; } else { List<String> subLetterCombo = letterCombinations(digits.substring(1)); for (String s : subLetterCombo) { for (int i = 0;i < digitLetters.length(); i++) { letterCombo.add(digitLetters.charAt(i) + s); } } return letterCombo; } } }
No comments:
Post a Comment