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

Title : Longest Common Prefix

Difficulty : EASY

Topic content :

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.

Translation : Given a string containing numbers 2-9, return all possible combinations of letters.

The mapping of numbers to letters (like buttons on a phone) is shown below. Note that 1 is not mapped to any letter.

 

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.

 

My thinking : First, you need to know what to do, then think about what data structure (list, stack, queue, heap, map, set) to use, and then think about what algorithm to use. Don't rush up and think about algorithms.

    What to do: Carry out all possible combinations according to the input numbers. Each of the data structures must be combined with several new characters, and the number of new character combinations is not certain, so a while loop must be used, and each variable After forming a new combination, you have to return to the original data structure, and the queue structure can be solved perfectly.

    Algorithm: First make an empty queue, loop for digits, look at the head of the queue, and see if its length is already i (within for), if it is, the head of the queue is out of the queue, and then take several characters corresponding to digits and add them here. After the string (the head of the line). And so on.

my code :

 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     }

Time complexity : O(3 n   +...+ 3 ) ≈ O(3 n   ) 3 is about 3 per key. n is the length of digits.

 

Answer :

Ahaha and I'm almost the same, so I won't post it~

That is, when converting from character to int, it uses:  int x = Character.getNumericValue(digits.charAt(i));   I don't know that Chracter has this method, so I wrote it down.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324692401&siteId=291194637