[leetcode 17]Letter Combinations of a Phone Number

1 题目:

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.

2 思路

好吧,想了半天,想不出来,参考别人的。

当时想着就是怎么每次循环,再一个字符串后面加一个字符。

看到别人的代码,处理的很好。

https://leetcode.com/discuss/24431/my-java-solution-with-fifo-queue

主要在ans.peek().length()==i、String t= ans.remove、链表上。

3 代码:

仿别人代码做的。

    public List<String> letterCombinations(String digits)
    {
        String[] maps = {" ","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        LinkedList<String> result = new LinkedList<String>();
        if (digits.isEmpty()) {
            return result;
        }
        result.add("");
        for (int i = 0; i < digits.length(); i++) {
            int index = Character.getNumericValue(digits.charAt(i));
            String num = maps[index];
            while (result.peek().length() == i) {
                String pre = result.removeFirst();
                for (Character character : num.toCharArray()) {
                    result.add(pre + character);
                }
            }
        }
        
        return result;
    }
原文地址:https://www.cnblogs.com/lingtingvfengsheng/p/4778830.html