Clean but verbose JAVA solution


  • 0
    C
    public class Solution
    {
        private List<String> list = new ArrayList<String>();
        
        public List<String> letterCombinations(String digits)
        {
            if(null == digits || digits.length() == 0)
            {
                return list;
            }
            
            int n = digits.length();
            
            ArrayList<String> strings = getStrings(digits);
            
            getCombinations("", strings, 0, n);
            
            return list;
        }
        
        private void getCombinations(String prefix, ArrayList<String> strings, int depth, int n)
        {
            if(depth == n)
            {
                list.add(prefix);
            }
            else
            {
                for(int i = 0; i < strings.get(depth).length(); i++)
                {
                    getCombinations(prefix + strings.get(depth).charAt(i), strings, depth + 1, n);
                }
            }
        }
        
        private ArrayList<String> getStrings(String digits)
        {
            ArrayList<String> alist = new ArrayList<String>();
            
            for(int i = 0; i < digits.length(); i++)
            {
                switch(digits.charAt(i))
                {
                    case '0': alist.add("0");
                        break;
                    case '1': alist.add("1");
                        break;
                    case '2': alist.add("abc");
                        break;
                    case '3': alist.add("def");
                        break;
                    case '4': alist.add("ghi");
                        break;
                    case '5': alist.add("jkl");
                        break;
                    case '6': alist.add("mno");
                        break;
                    case '7': alist.add("pqrs");
                        break; 
                    case '8': alist.add("tuv");
                        break;
                    case '9': alist.add("wxyz");
                        break;
                    
                }
            }
            
            return alist;
        }
    }

Log in to reply
 

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