ID | Title | Difficulty | |
---|---|---|---|
Loading... |
17. Letter Combinations of a Phone Number
Medium
LeetCode
Hash Table, String, Backtracking
Problem
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 1:
Input: digits = "23"
Output: ["ad","ae","af","bd","be","bf","cd","ce","cf"]
Example 2:
Input: digits = ""
Output: []
Example 3:
Input: digits = "2"
Output: ["a","b","c"]
Constraints:
- 0 <= digits.length <= 4
- digits[i] is a digit in the range [‘2’, ‘9’].
Code
- valueOf 和 getNumericValue
- valueOf 会返回数字对应的 ascii 码
public class test {
public static void main(String [] args){
char c = '5';
System.out.println(Character.getNumericValue(c));
System.out.println(Integer.valueOf(c));
// String 不会受到影响
String s = "5";
System.out.println(Integer.valueOf(s));
}
}
// 输出
// 5
// 53
// 5
class Solution {
public List<String> letterCombinations(String digits) {
if(digits == null || digits.length() == 0) return new ArrayList<>();
Queue<String> queue = new LinkedList<>();
String[] dict = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
queue.offer("");
for(int i = 0; i < digits.length(); i++) {
int index = digits.charAt(i) - '0';
String curr = dict[index];
while(queue.peek().length() == i) {
String temp = queue.poll();
for(char c : curr.toCharArray()){
queue.offer(temp + String.valueOf(c));
}
}
}
return new ArrayList<>(queue);
}
}
按 <- 键看上一题!
16. 3Sum Closest
按 -> 键看下一题!
18. 4Sum