[LeetCode][Java] Letter Combinations of a Phone Number

來源:互聯網
上載者:User

標籤:leetcode   java   letter combinations   

題目:

Given a digit string, 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.


Input:Digit string "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.

題意:

給定一個數字字串,返回這個數字能代表的所有的字母的組合。

數字對字母的映射如所示(就在電話的按鍵中)

Input:Digit string "23"Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
返回的結果可以按照任意的順序。

演算法分析:

 * 思路:


 *比如“234”這個字串,我可以先將0...1的所有排列找到-->{"a", "b", "c"}


 *再進一步將0...2的所有排列找到-->{"ad", "ae","af", "bd", "be", "bf", "cd", "ce", "cf"}


 *如此迴圈...直到字串末尾。實現如下

AC代碼:

public class Solution {    public  ArrayList<String> letterCombinations(String digits)     {    ArrayList<String> res=new ArrayList<String>();    String charmap[] = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};    if (digits.length()==0) return res;    res.add("");        for (int i = 0; i < digits.length(); i++)        {          ArrayList<String> tempres=new ArrayList<String>();           String chars = charmap[digits.charAt(i) - '0'];          for (int c = 0; c < chars.length();c++)          {            for (int j = 0; j < res.size();j++)              tempres.add(res.get(j)+chars.charAt(c));          }            res = tempres;        }        return res;    }}


著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] 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.