# 17. Letter Combinations of a Phone Number

XAMPP案例 189浏览

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.

clipboard.png

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.

Runtime: 2 ms, faster than 80.94% of Java online submissions for Letter Combinations of a Phone Number.
Memory Usage: 26.4 MB, less than 14.87% of Java online submissions for Letter Combinations of a Phone Number.

class Solution {
public List<String> letterCombinations(String digits) {
List<String> result = new ArrayList();
if (digits.isEmpty()) {
return result;
}

Map<Character, String> mcs = new HashMap<>();
mcs.put(’2′, “abc”);
mcs.put(’3′, “def”);
mcs.put(’4′, “ghi”);
mcs.put(’5′, “jkl”);
mcs.put(’6′, “mno”);
mcs.put(’7′, “pqrs”);
mcs.put(’8′, “tuv”);
mcs.put(’9′, “wxyz”);

StringBuilder s = new StringBuilder();
letterCombinations(digits, 0, mcs, result, s);

return result;
}

private void letterCombinations(String digits, int digitIdx, Map<Character, String> mcs, List<String> result, StringBuilder s) {
if (s.length() == digits.length()) {