1. 程式人生 > >[leetcode]17. Letter Combinations of a Phone Number手機鍵盤的字母組合

[leetcode]17. Letter Combinations of a Phone Number手機鍵盤的字母組合

poi clu char evel 個數字 The let alt input

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:

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.

題意:

給定一個數字串,看看有多少種對應的字母串。

思路:

Assumption:

字符串的合法性,是否包含1這個數字?如果包含,怎麽處理?同樣,輸入是否考慮 * 或 #?

空字符串怎麽處理?

多個解按什麽順序返回?

High Level帶著面試官walk through:

take "23" for example:

when index = 0, pointing to ‘2‘ in "23"

String letters = "abc"

for each char in letters,

add to path

move index forward, pointing to ‘3‘ in "23", recursively call the helper function to add every char of "def" to the path

代碼:

 1 class Solution {
 2     private static String[] keyboard =
 3
new String[]{ " ", "", "abc", "def", // ‘0‘,‘1‘,‘2‘,... 4 "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; 5 6 public List<String> letterCombinations(String digits) { //"23" 7 List<String> result = new ArrayList<>(); 8 if(digits.length() == 0 ) return result; 9 helper(digits, 0, "", result); 10 return result; 11 } 12 13 private void helper(String digits, int index, String path, List<String> result){ 14 if(index == digits.length()){ 15 result.add(path); 16 return; 17 } 18 19 String letters = keyboard[digits.charAt(index) - ‘0‘]; 20 for(int i = 0; i < letters.length(); i++ ){ 21 char c = letters.charAt(i); 22 helper(digits, index+1, path+c , result); 23 } 24 } 25 }

[leetcode]17. Letter Combinations of a Phone Number手機鍵盤的字母組合