LeetCode 17 -电话号码的字母组合

电话号码的字母组合——Letter Combinations of a Phone Number

题目

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
电话键图

递归解法


    public static List<String> solution1(String input) {
        List<String> res = new ArrayList<>();
        if (input.length() == 0){
            return res;
        }
        String pattern = "";
        combinationsProcess(pattern, input, 0, res);
        return res;
    }

    public final static String[] NUM_CHARS = {"" , "" , "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

    public static void combinationsProcess(String pattern, String digits, int flag, List<String> list){
        if (flag == digits.length()) {
            list.add(pattern);
            return;
        }

        String chars = NUM_CHARS[digits.charAt(flag) - '0'];
        if (chars.equals("")) {
            combinationsProcess(pattern, digits, flag + 1, list);
        }
        for (int i = 0; i < chars.length(); i++) {
            combinationsProcess(pattern + chars.charAt(i), digits, flag + 1, list);
        }
    }

压力测试情况

字符长度:10
18
_______________
字符长度:12
140
_______________
字符长度:15
21805

队列解法

参考他人代码


    public static List<String> solution2(String input) {
        if (input == null || input.equals("")) {
            return Collections.emptyList();
        }

        Queue<String> queue = new LinkedList<>();
        List<String> res;
        for (int i = 0; i < input.length(); i++) {
            queue_letterCombinations(queue, map.get(input.charAt(i)));
        }

        res = new ArrayList<>(queue.size());
        for (String s : queue) {
            res.add(s);
        }

        return res;
    }

    private static Queue<String> queue_letterCombinations(Queue<String> queue, String[] numChar) {
        if (queue.size() == 0) {
            for (int i = 0; i < numChar.length; i++) {
                queue.add(String.valueOf(numChar[i]));
            }
        } else {
            //对于后面到来字母,把queue出队列然后拼接以后进入队列
            //记录本次需要进行出列组合的元素数量
            int queueLength = queue.size();
            for (int i = 0; i < queueLength; i++) {
                //队列头元素出队列
                String s = queue.poll();
                for (int j = 0; j < numChar.length; j++) {
                    //将出来的队列元素和电话号码对应的字母依次进行拼接并添加进队列
                    queue.add(s + numChar[j]);
                }
            }
        }
        return queue;
    }

    public static final HashMap<Character, String[]> map = new HashMap<>();

    static {{
        map.put('2', new String[]{"a", "b", "c"});
        map.put('3', new String[]{"d", "e", "f"});
        map.put('4', new String[]{"g", "h", "i"});
        map.put('5', new String[]{"j", "k", "l"});
        map.put('6', new String[]{"m", "n", "o"});
        map.put('7', new String[]{"p", "q", "r", "s"});
        map.put('8', new String[]{"t", "u", "v"});
        map.put('9', new String[]{"w", "x", "y", "z"});
    }};

压力测试情况

字符长度:10
32
_______________
字符长度:12
178
_______________
字符长度:15
没出结果

迭代解法

按照《编程珠玑 第二版》代码调优法则,修改数据结构以及将递归重写为迭代整理而来,但是效果不是很理想,可能试验的数据结构不够多,不过,追求效率的代码使用最基础的数据类型真的是铁律!当然,有适用场景的权衡,实事求是就好。


        /**
     *
     * @param input
     * @return
     *
     */
    public static List<String> solution2(String input) {
        int len = 1;
        char[] chars = input.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            len *= chars[i] == '7'|| chars[i] == '9' ? 4 : 3;
        }
        /*String[] res = new String[len];
        int interval3 = len/3, interval4 = len/4;
        for (int i = 0; i < chars.length; i++) {
            String[] values = map.get(chars[i]);
            int interval = values.length == 4 ? interval4 : interval3;
            for (int j = 0; j < values.length; j++) {
                for (int k = 0; k < interval; k++) {
                    String value = i == 0 ? new String() : res[j];
                    value += values[j];
                    res[j] = value;
                }
            }
        }*/

        char[][] charsRes = new char[len][chars.length];
        int interval3 = len/3, interval4 = len/4;
        for (int i = 0; i < chars.length; i++) {
            char[] values = characterHashMap.get(chars[i]);
            int interval = values.length == 4 ? interval4 : interval3;
            for (int j = 0; j < values.length; j++) {
                int start = j * interval;
                int end = (j + 1) * interval;
                for (int k = start; k < end; k++) {
                    char[] value = charsRes[k];
                    value[i] = values[j];
                }
            }
        }

        List<String> res = new ArrayList<>(len);
        // for循环消耗大量时间-420ms,循环体在次数超过3万后性能下降
        // foreach循环消耗大量时间-431ms,循环体在次数超过3万后性能下降
        // IntStream总体较好,但循环次数较少时不建议使用
        /*for (int i = 0; i < len; i++) {
            res.add(new String(charsRes[i]));
        } */
        // 这种方式相比于while、for、foreach循环快了近一倍 降到200ms
        IntStream.range(0, len).forEach(i -> res.add(String.valueOf(charsRes[i])));

        return res;
    }

压力测试情况

字符长度:10
17-> 80(IntSream) -> 19(foreach)
_______________
字符长度:12
580——> 421(使用IntSream) -> 593(foreach)
_______________
字符长度:15
没出结果

其他解法没研究出来,动态规划适合直接得出结果,不太注重过程(可能我水平不够也不一定),又看了《计算机程序设计艺术——卷4A 组合》很久,也没研究出来,惭愧啊0.0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值