zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【算法hot-17】电话号码的字母组合

算法 17 hot 电话号码
2023-09-27 14:29:28 时间

电话号码的字母组合

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

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

public class LC006_17_letterCombinations {
    public static void main(String[] args) {
        List<String> ans = letterCombinations("23");
        System.out.println(ans.size());
        for (String string : ans) {
            System.out.println(string + " ");
        }
    }
    public static List<String> letterCombinations(String digits) {
        //特殊情况
        if (digits == null || digits.length() == 0) {
            return new ArrayList<>();
        }
        String[] letter_map = {" ", "*", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        List<String> ans = new ArrayList<>();
        ans.add("");
        //遍历字符串的长度
        for (int i = 0; i < digits.length(); i++) {
            //遍历ans的长度
            int size = ans.size();
            for (int j = 0; j < size; j++) {
                String temp = ans.remove(0);
                //获取当前的字符串
                String s = letter_map[digits.charAt(i) - '0'];
                //遍历当前字符串的长度
                for (int k = 0; k < s.length(); k++) {
                    ans.add(temp + s.charAt(k));
                }
            }
        }
        return ans;
    }
}