Letter Combinations of a Phone Number

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.

Letter Combinations of a Phone Number_第1张图片

Input:Digit string "23"`这里写代码片`
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
public List<String> letterCombinations(String digits) {
        LinkedList<String> ans = new LinkedList<String>();
        String[] mapping = new String[]{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        ans.add("");
        for (int i = 0; i < digits.length(); i++) {
            int x = Character.getNumericValue(digits.charAt(i));
            while (ans.peek().length() == i) {
                String t = ans.remove();
                for (char s : mapping[x].toCharArray())
                    ans.add(t + s);
            }
        }
        if (ans.peek().length() == 0)
            ans.remove();
        return ans;
    }

你可能感兴趣的:(leetcode)