题解 | #牛名生成器#

牛名生成器

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);
            }
        }

    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 12:11
点赞 评论 收藏
分享
强大的马里奥:不太可能,我校计算机硕士就业率99%
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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