Given a string containing only the numbers 2-9, return all the letter combinations it can represent.
The mapping of numbers to letters is given as follows (same as a telephone key). Note that 1 does not correspond to any letter.
Example:
Input: “23” output: [” AD “, “ae”, “af”, “bd”, “be”, “bf”, “CD” and “ce”, “cf”]. Note: Although the above answers are in lexicographical order, you can choose the order in which the answers are printed.
Source: LeetCode link: leetcode-cn.com/problems/le…
Their thinking
Queue-like methods
- Check whether the incoming is null
- Initialize collection
- An array of data
- Iterating to get a single character of the string into an int
- We take the int that we just got, we get the data from the array, and the subscript is the value of the int
- The loop takes the elements of the set and compares them with the loop’s traversal I. For example, passing 34, the first pass, getting a single character 3, taking the array’s data “def”, link.peek() getting “”, length 0
- Record removed “”
- Separate “def” and loop into sets, respectively “d”, “e”, “f”.
Peek () gets “D” again. Go down, delete and record d, and enter the loop with “ghi”. Add “dg”, “dh”, “di”. Take the “e” in the second loop, and do the same thing.
public List<String> letterCombinations(String digits) { LinkedList<String> link = new LinkedList<>(); / / 1if(digits.isEmpty()) {
return link;
}
// 2
link.add("");
// 3
String[] result = {"0"."1"."abc"."def"."ghi"."jkl"."mno"."pqrs"."tuv"."wxyz"};
for(int i = 0; i < digits.length(); i++) { // 4 int x = Character.getNumericValue(digits.charAt(i)); // 5 String s = result[x]; / / 6while(link.peek().length() == i) { // 7 String e = link.remove(); / / 8for(char c : s.toCharArray()) { // 9 link.add(e+c); }}}return link;
}
Copy the code