recursion java stringbuilder


  • 0
    I
    public class Solution {
        public List<String> letterCombinations(String digits) {
            if(digits.isEmpty()) {
                return new ArrayList<String>();
            }
            
            HashMap<Character, String> map = new HashMap<Character, String>();
            map.put('2', "abc");
            map.put('3', "def");
            map.put('4', "ghi");
            map.put('5', "jkl");
            map.put('6', "mno");
            map.put('7', "pqrs");
            map.put('8', "tuv");
            map.put('9', "wxyz");
            
            
            StringBuilder sb = new StringBuilder("");
            ArrayList<String> combos = new ArrayList<String>();
            combo(combos, map, sb, 0, digits);
            
            return combos;
        }
        
        private void combo(ArrayList<String> combos, HashMap<Character, String> map, StringBuilder sb, int pos, String digits) {
            if(pos == digits.length()) {
                combos.add(sb.toString());
                return;
            }
            
            for(char c : map.get(digits.charAt(pos)).toCharArray()) {
                sb.append(c);
                combo(combos, map, sb, pos + 1, digits);
                sb.setLength(sb.length() -1);
            }
        }
    }
    

Log in to reply
 

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