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"]. Note: Although the above answer is in lexicographical order, your answer could be in any order you want.

Solution

public class Solution {
    public List<String> letterCombinations(String digits) {
        digits = digits.trim();
        if(digits.length() == 0) return new ArrayList<String>();
        for(int i = 0; i < digits.length(); i++) {
            int digit = digits.charAt(i) - '0';
            if(digit < 2 || digit > 9) return new ArrayList<String>();
        }
        ArrayList<String> res = new ArrayList<String>();
        walkThroughDigits("", digits, 0, res);
        return res;
    }

    public String trans[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    void walkThroughDigits(String currentStr, String digits, int index, ArrayList<String> res) {
        if(index == digits.length()) {
            res.add(currentStr);
            return;
        }
        int digit = digits.charAt(index) - '0';
        String translation = trans[digit - 2];
        for(int i = 0; i < translation.length(); i++) {
           walkThroughDigits(currentStr + translation.charAt(i), digits, index + 1, res);
        }
    }
}

results matching ""

    No results matching ""