17. 电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.*;

class Solution {

    private static final Map<Character, char[]> map;

    static {
        map = new HashMap<>();
        map.put('2', new char[]{'a', 'b', 'c'});
        map.put('3', new char[]{'d', 'e', 'f'});
        map.put('4', new char[]{'g', 'h', 'i'});
        map.put('5', new char[]{'j', 'k', 'l'});
        map.put('6', new char[]{'m', 'n', 'o'});
        map.put('7', new char[]{'p', 'q', 'r', 's'});
        map.put('8', new char[]{'t', 'u', 'v'});
        map.put('9', new char[]{'w', 'x', 'y', 'z'});
    }

    private List<String> ret;

    private LinkedList<Character> path;

    public Solution() {
        this.ret = new ArrayList<>();
        this.path = new LinkedList<>();
    }

    private String getPath() {
        StringBuilder sb = new StringBuilder();
        for (Character character : path) {
            sb.append(character);
        }
        return sb.toString();
    }

    private void solve(String digits, int index) {
        if (index == digits.length()) {
            ret.add(getPath());
            return;
        }

        char digit = digits.charAt(index);
        for (char c : map.get(digit)) {
            path.offerLast(c);
            solve(digits, index + 1);
            path.pollLast();
        }
    }

    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) {
            return ret;
        }

        solve(digits, 0);

        return ret;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            new Solution().letterCombinations(in.next()).forEach(System.out::println);
        }
    }
}
posted @ 2021-12-16 14:51  Tianyiya  阅读(65)  评论(0)    收藏  举报