题解 | #牛名生成器#

牛名生成器

https://www.nowcoder.com/practice/f82fe408de8f4fbdbc30162d6b3e65bb

考察回溯法

方法:用哈希表存储数字对应的字母后,不断进行组合排列。顺序处理每一个数字,并且每次从哈希表取出一个数字所对应的所有字母,将字母插入到已有的字母后面,处理完所有数字后就得到完整的数字对应字母的排列了。

用Java语言,代码如下所示:

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param digits string字符串 
     * @return string字符串一维数组
     */
    public String[] letterCombinations (String digits) {
        // write code here
        List<String> combinations = new ArrayList<String>();
        if (digits.length() == 0) {
            return new String[0];
        }
        Map<Character, String> phoneMap = new HashMap<Character, String>() {{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};
        backtrack(combinations, phoneMap, digits, 0, new StringBuffer());
        String[] res = new String[combinations.size()];
        for(int i=0; i<combinations.size(); i++){
            res[i] = combinations.get(i);
        }
        return res;
    }

    public void backtrack(List<String> combinations, Map<Character, String> phoneMap, String digits, int index, StringBuffer combination) {
        if (index == digits.length()) {
            combinations.add(combination.toString());
        } else {
            char digit = digits.charAt(index);
            String letters = phoneMap.get(digit);
            int lettersCount = letters.length();
            for (int i = 0; i < lettersCount; i++) {
                combination.append(letters.charAt(i));
                backtrack(combinations, phoneMap, digits, index + 1, combination);
                combination.deleteCharAt(index);
            }
        }

    }
}

全部评论

相关推荐

27届毕业,最近想找一段大厂实习,感觉简历有些问题,好多都不给面,求大佬们指点,最近好焦虑
重生之我学Java干...:我从后端的角度分析一下你的第一个项目,我感觉亮点不是很突出。因为我是因为组内有需求,临时上手学react干活。我用到的技术基本就cover你那个智慧园区管理平台的很多亮点了。那作为比较专业的前端,你上述的内容是不是有点单薄呢。感觉还得包装
点赞 评论 收藏
分享
迷茫的大四🐶:当你得到一些东西,那这些东西就会变成基本项,你有别人也有
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务