题解 | #牛名生成器#
牛名生成器
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[] ans = new String[combinations.size()]; 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); } } } }#题解#