【LeetCode】17. Letter Combinations of a Phone Number - Java实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaoguaihai/article/details/84276009

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;
}

猜你喜欢

转载自blog.csdn.net/xiaoguaihai/article/details/84276009
今日推荐