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.

Input:Digit string “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

class Solution {
     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//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);//数字键上的每一个字符都加上去
        }
    }
    return ans;
}
}

解析:例如 加入输入的是“23”
1、第一个进入 ans.peek().lenght=0,也就是什么都没,
2、String t = ans.remove();取出链表头的字符也就是“”
3、for(char s:mapping[x].toCharArray())实际上就是将2对应的 ‘a’,’b’ ,’c’,依次放到队列中
此时ans = {‘a’,’b’,’c’};
4、i++ ,此时变成第二个数字3对应的
5、此时ans.peek().length()=’a’.length()==1==i String t = ans.remove()==’a’;
6、执行for后 新如队列的有 “ad”,”ae”,”af”
7、执行第五步。。。取得”b”……

你可能感兴趣的:(leetcode)