17. Letter Combinations of a Phone Number

栏目: ASP.NET · 发布时间: 5年前

内容简介: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.

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.

17. Letter Combinations of a Phone Number

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.

难度:medium

题目:

给定字符串包含数字2到9,返回所有字母组合。数字字母的对应关系如下图所示。注意1不与任何字母对应。

思路:

组合,递归

Runtime: 2 ms, faster than 80.94% of Java online submissions for Letter Combinations of a Phone Number.

Memory Usage: 26.4 MB, less than 14.87% of Java online submissions for Letter Combinations of a Phone Number.

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList();
        if (digits.isEmpty()) {
            return result;
        }
        
        Map<Character, String> mcs = new HashMap<>();
        mcs.put('2', "abc");
        mcs.put('3', "def");
        mcs.put('4', "ghi");
        mcs.put('5', "jkl");
        mcs.put('6', "mno");
        mcs.put('7', "pqrs");
        mcs.put('8', "tuv");
        mcs.put('9', "wxyz");
        
        StringBuilder s = new StringBuilder();
        letterCombinations(digits, 0, mcs, result, s);

        return result;
    }
    
    private void letterCombinations(String digits, int digitIdx, Map<Character, String> mcs, List<String> result, StringBuilder s) {
        if (s.length() == digits.length()) {
            result.add(s.toString());
            return;
        }
        char[] cs = digits.toCharArray();
        for (int i = digitIdx; i < cs.length; i++) {
            String str = mcs.get(cs[i]);
            for (int j = 0; j < str.length(); j++) {
                s.append(str.charAt(j));
                letterCombinations(digits, i + 1, mcs, result, s);
                s.deleteCharAt(s.length() - 1);
            }
        }
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

算法交易与套利交易

算法交易与套利交易

赵胜民 / 厦门大学出版社 / 2010-9 / 35.00元

《算法交易与套利交易》主要介绍算法交易和一些套利交易的策略,以便于读者对相关方面的内容进行阅读和学习。在《算法交易与套利交易》的第一部分,我们回顾了投资学一些相关的基本内容。其中,前两章介绍了证券投资的收益和风险等特征,以及马可维茨的最优资产配置模型。第3章则介绍了股票投资分析当中常用的资本资产定价模型(CAPM)、套利定价模型(APT),以及因素模型。然后,第4、5章分别讲到了金融证券估值模型、......一起来看看 《算法交易与套利交易》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试