My 4ms Java Solution


  • 0
    A
    public class Solution {
        public List<String> letterCombinations(String digits) {
            String[] sa = {"0", "1", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
            List<String> result = new ArrayList<>();
            if(digits.equals("")) return result;
            
            char[] s = sa[digits.charAt(0) - '0'].toCharArray();
            for(char c : s) {
                result.add(String.valueOf(c));
            }
            
            for(int i=1;i<digits.length();i++) {
                combine(result, sa[digits.charAt(i) - '0'].toCharArray());
            }
            return result;
        }
        
        private void combine(List<String> result, char[] cc) {
            int length = result.size();
            for(int i=0;i<length * (cc.length-1);i++) {
                result.add(result.get(i % length));
            }
            for(int i=0;i<cc.length;i++) {
                for(int j=0;j<length;j++) {
                    result.set(i * length + j, result.get(i * length + j) + cc[i]);
                }
            }
        }
    }
    

Log in to reply
 

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