Java solution using recursion and easy to understand


  • 0
    K
    public List<String> letterCombinations(String digits) {
        List<String> result = null;
        if(digits == null || digits.equals("")) return new ArrayList<String>(1);
        char[] cs = digits.toCharArray();
        result = getString(new ArrayList<String>(1),cs,0);
        return result;
    }
    
    public char[] getChar(char c){
        switch (c){
            // case '1': return new char[]{'o'};
            case '2': return new char[]{'a','b','c'};
            case '3': return new char[]{'d','e','f'};
            case '4': return new char[]{'g','h','i'};
            case '5': return new char[]{'j','k','l'};
            case '6': return new char[]{'m','n','o'};
            case '7': return new char[]{'p','q','r','s'};
            case '8': return new char[]{'t','u','v'};
            case '9': return new char[]{'w','x','y','z'};
            // case '0': return new char[]{' '};
            // case '*': return new char[]{'+'};
            // case '#': return new char[]{' '};
            default:return null;
        }
    }
    
    public List<String> getString(List<String> oldStr,char[] c,int index){
        if(index < c.length) {
            char[] ca = getChar(c[index]);
            if (ca != null) {
                List<String> newStr = new ArrayList<String>(oldStr.size() * ca.length);
                for (int i = 0; i < ca.length; i++) {
                    if(index == 0){
                        newStr.add("" + ca[i]);
                    }else{
                        Iterator<String> it = oldStr.iterator();
                        while (it.hasNext()) {
                            String str = it.next();
                            newStr.add(str + ca[i]);
                        }
                    }
                }
                return getString(newStr, c, ++index);
            } else {
                return oldStr;
            }
        }else{
            return oldStr;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.