美文网首页
电话号码的字母组合

电话号码的字母组合

作者: 二进制的二哈 | 来源:发表于2019-11-29 18:48 被阅读0次

题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

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

示例.png

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
说明:
尽管上面的答案是按字典序排列的,但是你可以任意选择答案输出的顺序。

Java代码:

class Solution {
    public List<String> letterCombinations(String digits) {
        if(digits == null || digits.length() == 0)
            return new ArrayList();
        if(digits.length() == 1){
            //仅有一位时
            return getList(digits.charAt(0));
        }

        int i = 0;
        List<String> ans = null;
        while(i < digits.length()){
            char c = digits.charAt(i);
            List<String> leftList = getList(c);
            if(i == 0){
                ans = merge(leftList,getList(digits.charAt(i+1)));
            }else if(i != digits.length() -1 ){
                ans = merge(ans,getList(digits.charAt(i+1)));
            }
            i++;
        }
        return ans;
    }

    private List<String> getList(char c){
        List<String> ans = null;
        switch(c){
            case '2':
                ans = Arrays.asList("a","b","c");
                break;
            case '3':
                ans = Arrays.asList("d","e","f");
                break;
            case '4':
                ans = Arrays.asList("g","h","i");
                break;
            case '5':
                ans = Arrays.asList("j","k","l");
                break;
            case '6':
                ans = Arrays.asList("m","n","o");
                break;
            case '7':
                ans = Arrays.asList("p","q","r","s");
                break;
            case '8':
                ans = Arrays.asList("t","u","v");
                break;
            case '9':
                ans = Arrays.asList("w","x","y","z");
                break;
        }
        return ans;
    }

    private List<String> merge(List<String> left,List<String> right){
        if(right == null)
            return left;
        List<String> newList = new ArrayList<>();
        for(String l : left){
            for(String r : right){
                newList.add(l+r);
            }
        }
        return newList;
    }
}

相关文章

网友评论

      本文标题:电话号码的字母组合

      本文链接:https://www.haomeiwen.com/subject/jkngwctx.html