1. 程式人生 > >【LeetCode】17. Letter Combinations of a Phone Number - Java實現

【LeetCode】17. Letter Combinations of a Phone Number - Java實現

文章目錄

1. 題目描述:

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.

2. 思路分析:

題目的意思是電話的號碼按鈕上每個數字按鈕中都包含了幾個英文字母(除了1按鈕),給定給定一串數字,求出這些數字按鈕上表示的英文字母的所有組合。

可以採用遞迴思想來求解,思路簡單,見具體實現程式碼。

3. Java程式碼:

原始碼見我GiHub主頁

程式碼:

public static List<String> letterCombinations(String digits) {
    String[] buttons = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    List<String> result = new ArrayList<>();

    if (digits.length() == 0) {
        return
result; } // 第一個數字所在的按鈕上對應的字母 String firstLetters = buttons[digits.charAt(0) - '0']; // 如果長度為1,則將該按鈕上的字母分別返回即可 if (digits.length() == 1) { for (int i = 0; i < firstLetters.length(); i++) { result.add(firstLetters.substring(i, i + 1)); } return result; } // 如果長度大於1,則遞迴求解 List<String> combinations = letterCombinations(digits.substring(1)); for (int i = 0; i < firstLetters.length(); i++) { String letter = firstLetters.substring(i, i + 1); for (String combination : combinations) { result.add(letter + combination); } } return result; }