17. Letter Combinations of a Phone Number(medium)

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.

17. Letter Combinations of a Phone Number(medium)_第1张图片

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.

分析:
给一串数字,求出所有可能拼出来的组合。先把第一个数字的所有可能写到list中,再遍历这个list,把第二个数字的所有可能加到后面,以此类推。

Java语言:

    String[] mapping = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};

    public List letterCombinations(String digits) {
        List res = new ArrayList<>();
        if (digits == null || "".equals(digits)) {
            return res;
        }
        res.add("");//注意此处需要先加一个空字符串,否则后面无法遍历这个list
        for (int i = 0; i < digits.length(); i++) {
            res = expand(res, digits.charAt(i) - '0');
        }
        return res;
    }

    public List expand(List list, int i) {
        List res = new ArrayList<>();
        char[] chars = mapping[i].toCharArray();
        for (String str : list) {
            for (char c : chars) {
                res.add(str + c);
            }
        }
        return res;
    }

你可能感兴趣的:(17. Letter Combinations of a Phone Number(medium))