leetcode 17. Letter Combinations of a Phone Number

Given a string containing digits from 2-9 inclusive, 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. Note that 1 does not map to any letters.

Example:

Input: "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.

 

用到了LinkedList的add和remove,最精髓的是从左到右一个一个数字慢慢按queue的方式累加上去。

class Solution {
    public List<String> letterCombinations(String digits) {
        LinkedList<String> ans = new LinkedList<>();
        if(digits.isEmpty()) return ans;
        String[] map = 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){ //很难想到的一行代码,其中peek()是指取list中的第一个元素
                String t = ans.remove();
                for(char c: map[x].toCharArray()){
                    ans.add(t+c);
                }
            }
        }
        return ans;
        
    }
}

 

posted @ 2019-02-20 22:31  JamieLiu  阅读(101)  评论(0)    收藏  举报