(Java)LeetCode-17. Letter Combinations of a Phone Number__Java

來源:互聯網
上載者:User

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.

這一題也是蠻簡單滴,無非是幾重迴圈即可搞定,為了麻煩麻煩自己,採用了遞迴的想法,雖然代碼簡單了些,犧牲了空間和時間


public class Solution {    char[][] a = {{},{},{'a','b','c'},{'d','e','f'},{'g','h','i'},{'j','k','l'},{'m','n','o'},{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'}};public List<String> letterCombinations(String digits) {        if(digits.length() == 0){        return new ArrayList<String>();        }        if(digits.length() == 1){        List<String> result = new ArrayList<String>();        int i = Integer.parseInt(digits);        for(char c : a[i]){        result.add(Character.toString(c));        }        return result;        }        int j = Integer.parseInt(digits.substring(0,1));        List<String> res = new ArrayList<String>();        for(char c : a[j]){        for(String ss : letterCombinations(digits.substring(1))){        res.add(c+ss);        }        }return res;    }}


附上大神的遞迴,速度很快~


public List<String> letterCombinations(String digits) {    List<String> list = new ArrayList<String>();    if(!digits.isEmpty()) {        helper(digits, "", 0, list);    }    return list;}public void helper(String digits, String combo, int position, List<String> list) {    if(position == digits.length()) {        list.add(combo);        return;    }    String[] letters = getMapping(digits.charAt(position));    for(int i = 0; i < letters.length; i++){        helper(digits, combo + letters[i], position + 1, list);    }}public String[] getMapping(char c) {    switch (c) {    case '2':        return new String[] {"a", "b", "c"};    case '3':        return new String[] {"d", "e", "f"};    case '4':        return new String[] {"g", "h", "i"};    case '5':        return new String[] {"j", "k", "l"};    case '6':        return new String[] {"m", "n", "o"};    case '7':        return new String[] {"p", "q", "r", "s"};    case '8':        return new String[] {"t", "u", "v"};    case '9':        return new String[] {"w", "x", "y", "z"};    }    return new String[] {};}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.