标签:dig http etc import let list == 个数 时空
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /* * 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. 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. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class Lc17 { public static List<String> letterCombinations(String digits) { // 避免频繁扩容 LinkedList<String> ans = new LinkedList<String>(); String[] mapping = new String[] { "0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; // 空判断 if (digits.length() == 0) { return new ArrayList<>(); } // 这里是利用队列的特性进行bfs遍历 ans.add(""); // 由于不知道具体由多少个数字,所以用for控制 for (int i = 0; i < digits.length(); i++) { // 找到对应数字 ,比如输入23 ,找到2或者3 int x = Character.getNumericValue(digits.charAt(i)); /* * 当第0次循环时,队列中的元素长度时空 即0位 * 当第一次循环时,队列中元素长度时a/b/c,即1位。以此类推 */ while (ans.peek().length() == i) { // 获取队列中的元素,并移除该元素重新组合 String t = ans.remove(); for (Character ch : mapping[x].toCharArray()) { ans.add(t + ch); } } } return ans; } public static void main(String[] args) { String digits = "23"; System.out.println(letterCombinations(digits)); } }
标签:dig http etc import let list == 个数 时空
原文地址:https://www.cnblogs.com/xiaoshahai/p/12182608.html