Share my AC Java code. Is there any improvement?


  • 0
    P
    public List<String> letterCombinations(String digits) {
        int len = digits.length();
        List<String> re = new ArrayList<String>();
        re.add("");
        for (int i = 0; i < len; i++) {
            int value = Integer.parseInt(digits.substring(i, i + 1));
            re = addList(re, value - 2);
        }
        return re;
    }
    
    public List<String> addList(List<String> old, int index) {
        String[] map = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        int tag = 3;
        if (index == 7 || index == 5) {tag++;}
        List<String> mynew = new ArrayList<String>();
        for (int m = 0; m < tag; m++) {
            List<String> temp = new ArrayList<String>();
            temp.addAll(old);
            for (String item : temp) {
               item += map[index].substring(m, m + 1);
               mynew.add(item);
           }
        }
        return mynew;
    }
    

    suppose only 2~9 will be used, there are two special cases, which are 7 and 9.


Log in to reply
 

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