题解 | #牛名生成器#

牛名生成器

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

  1. 题目考察的知识点

回溯,哈希表的使用

  1. 题目解答方法的文字分析

使用哈希表存储每个数字对应的所有可能的字母,然后进行回溯操作。通过回溯穷举所有可能的解,然后将解存进combinations中。

回溯过程中维护一个StringBuffer,表示已有的字母排列(如果未遍历完电话号码的所有数字,则已有的字母排列是不完整的)。该StringBuffer初始为空。每次取电话号码的一位数字,从哈希表中获得该数字对应的所有可能的字母,并将其中的一个字母插入到已有的字母排列后面,然后继续处理电话号码的后一位数字,直到处理完电话号码中的所有数字,即得到一个完整的字母排列。

  1. 本题解析所用的编程语言

java

  1. 完整且正确的编程代码
import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param digits string字符串
     * @return string字符串一维数组
     */
    public String[] letterCombinations (String digits) {
        //用list存储所有组合
        List<String> combinations = new ArrayList<String>();
        //数字长度为0时,字符串数组为空
        if (digits.length() == 0) {
            return  new String[0];
        }
        //用HashMap存储,每个电话数字对应的字符
        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[] ans = new String[combinations.size()];
        //list转化成数组
        for (int i = 0; i < combinations.size(); i++) {
            ans[i] = combinations.get(i);
        }
        return ans;
    }
    
    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);
            }
        }
    }
}
全部评论

相关推荐

牛客小菜鸡66:boss里面,招人的叫老板,找工作的叫牛人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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