How can I improve this Simple Java solution?


  • 0
    A
    public class Solution {
        public static HashMap<Character, List<Character>> hm = new HashMap<Character,List<Character>>();
        public static List<String> letterCombinations(String digits) {
            hm.put('2',Arrays.asList('a','b','c'));
            hm.put('3',Arrays.asList('d','e','f'));
            hm.put('4',Arrays.asList('g','h','i'));
            hm.put('5',Arrays.asList('j','k','l'));
            hm.put('6',Arrays.asList('m','n','o'));
            hm.put('7',Arrays.asList('p','q','r','s'));
            hm.put('8',Arrays.asList('t','u','v'));
            hm.put('9',Arrays.asList('w','x','y','z'));
            List<String> li = new ArrayList<String>();
            getCombinations ("",digits, li);
            return li;
        }
        
        public static void getCombinations(String prefix, String input, List<String> li){
            if (input.isEmpty()){
                if (!prefix.isEmpty()){
                    li.add(prefix);
                }
            }
            else {
                for (char c : hm.get(input.charAt(0))){
                    prefix += c;
                    getCombinations(prefix,input.substring(1,input.length()),li);
                    prefix = prefix.substring(0,prefix.length() - 1);
                }
            }
        }
    }

Log in to reply
 

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