LeetCode第[17]题(Java):Letter Combinations of a Phone Number

题目:最长公共前缀

难度:EASY

题目内容

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.

翻译:给定一个包含2-9包含数字的字符串,返回所有可能表示的字母组合。

数字到字母的映射(就像电话上的按钮一样)如下所示。注意,1没有映射到任何字母。

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.

我的思路:首先要知道要做什么,再思考用什么数据结构(list、栈、队列、堆、map、set),再思考用什么算法。不要冲上来就想着算法。

    做什么,用什么做:根据输入的数字进行所有可能搭配,数据结构中每一个都要和新来的几个字符进行组合字符,而且新来字符组合数目并不确定,所以得采用while循环,并且每一个变成新的组合后又得回到原来的数据结构,队列结构就能完美解决。

    怎么做:首先弄一个空队列,for对digits循环,看队头,看它的长度是否已经是 i 个(for内),是则队头出队,再取digit对应的几个字符分别加在此字符串(队头)的后面。以此类推。

我的代码:

 1     public List<String> letterCombinations(String digits) {
 2         LinkedList<String> ans = new LinkedList<String>();
 3         if(digits.isEmpty()) return ans;
 4         String[] mapping = new String[] {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
 5         ans.add("");
 6         for(int i = 0; i < digits.length(); i++){
 7             int x = Integer.parseInt(digits.charAt(i)+"");
 8             while(ans.peek().length() == i){
 9                 String t = ans.poll();
10                 for(char s : mapping[x - 2].toCharArray())
11                     ans.offer(t+s);
12             }
13         }
14         return ans;
15     }

时间复杂度:O(3n  +。。。+ 3 ) ≈ O(3n  )    3是每个按键大概是3个。 n是digits的长度。

答案

啊哈哈和我几乎一样,就不贴出来了~

就是在从字符转int的时候它使用的是:  int x = Character.getNumericValue(digits.charAt(i));  不知道Chracter有这个方法,记下了。

原文地址:https://www.cnblogs.com/Xieyang-blog/p/8906417.html