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

來源:互聯網
上載者:User

標籤:war   phi   code   margin   etc   note   one   ppi   pos   

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這個數字?如果包含,怎麼處理?同樣,輸入是否考慮 * 或 #?

Null 字元串怎麼處理?

多個解按什麼順序返回?

 

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手機鍵盤的字母組合

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.