LeetCode:17. Letter Combinations of a Phone Number(Medium)

1. 原题链接

https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/

2. 题目要求

给定一个数字字符串digits,每一个数字对应拨号键盘上的数字,每个数字又对应不同的字母。例如“3”对应“d“、“e”、“f”三个字母。输出digits所含数字对应的所有字母组合。

例如,digits="23",输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]

3. 解题思路

思路一:采用多重for循环暴力解决,但是时间复杂度为O(nx),x为digits字符串中包含的数字个数。

思路二:使用队列的思想,首先建立一个空的LinkedList列表对象res,在res中加入“”,避免第一次for循环时从res中取出对象时报空指针异常

使用for循环,用peek( )方法从res中将列表的头元素取出,并将digits的第一个数字对应的字母依次插入头元素后面;最后重新加入到res中。

4.代码实现

import java.util.LinkedList;
import java.util.List;

public class LetterCombinationsOfPhoneNumber17 {
    public static void main(String[] args) {
        List<String> ls = LetterCombinationsOfPhoneNumber17.letterCombinations("23");
        for (String str : ls) {
            System.out.println(str);
        }
    }

    public static List<String> letterCombinations(String digits) {
        LinkedList<String> res = new LinkedList<>();
        String[] mapping = new String[]{"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

        if (digits.length() != 0) { // 入过digits为空直接返回空的res
            res.add("");
            for (int i = 0; i < digits.length(); i++) {
                int x = Character.getNumericValue(digits.charAt(i));
                while (res.peek().length() == i) {  // 判断该次组合是否完成
                    String t = res.remove();   // 从队列中取出队头元素,先进先出
                    for (char s : mapping[x].toCharArray()) {  // 将该数组对应的字符串转换成字符数组,进行遍历
                        System.out.println("t+s:"+t + s);
                        res.add(t + s);  // 在原有字符串后加入新的字符,然后重新加入队列
                    }
                }
            }
            return res;
        } else {
            return res;
        }
    }
}

  

 

posted @ 2017-12-22 14:06  一只敲码的猫  阅读(248)  评论(0编辑  收藏  举报