LeetCode(17)-Letter Combinations of a Phone Number

版权声明:XiangYida https://blog.csdn.net/qq_36781505/article/details/83387313

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.

这个题的大概意思是:给一个一串数字的字符串(2~9),然后里面的数字代表手机9键中的键盘,
每一个键中都有对应的字母,然后要求输出所有的字母组合。
这个题考的就是数学中的排列组合,这里讲一下LeeCode上投票最多的一个解法,挺棒的。
先贴出代码吧

public List<String> letterCombinations(String digits) {
           LinkedList<String> ans = new LinkedList<String>();
           if(digits.isEmpty()) return ans;
           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);
               }
           }
           return ans;
}
  • 大致思路如下:

  • 我们以题目给的例子来进行单步调试,首先创建一个LinedList作为一个队列,然后创建一个String数字将数字与字母
    相映射。

  • 先看最外层的的循环,这层循环就是“遍历按键”,然后将按键中的字母依次放入队列中
    我们将这里的LindList理解为队列,事实上LinedList实现了Queue接口)
    avatar)

  • 放入后跳出while循环

    在这里插入图片描述

  • 进入外层for循环的第二重,这里就比较关键了,这里我们来仔细研究一下

    • 此时i=1,i表示的是队列中每个元素的长度。
    • while循环的条件是队列中“对头”的元素长度等于i,此时队列头元素为“a”长度为1,
     String t = ans.remove();
  • 这行语句实际上有2个操作,先将对头的元素出队,然后复制给t,然后我们接着看这段代码
     for(char s : mapping[x].toCharArray())
           ans.add(t+s);
  • 首先是遍历第二个按键中的字母然后与t进行组合,然后依次加入队尾
    在这里插入图片描述
  • 然后此重循环结束后,进入外层for循环的下一重,大致就是这样
    • b出队,然后将下一个按键对应的字母一直组合
    • c出队 ··
  • 就这样实现了所有的组合

猜你喜欢

转载自blog.csdn.net/qq_36781505/article/details/83387313