My answer inspired by highest vote answer (JAVA)


  • 0
    M
    public List<String> letterCombinations(String digits) {
        List<String> result = new ArrayList<String>();
        String[] map = {"0","1","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        
        for(int i = 0; i < digits.length(); i++){
            // loop through each digit in string
            int curNum = Character.getNumericValue(digits.charAt(i));
            String psbLetter = map[curNum];
            char[] letterArray = psbLetter.toCharArray();
            
            while( result.size() == 0 ||result.get(0).length() == i){
                // remove previous unfinished string
                String addToString = "";
                if( result.size() != 0 ){
                     addToString = result.remove(0);
                }
                
                for(int j = 0; j < letterArray.length; j++){
                    // add letter to each previous unfinished string
                    String comb = addToString + letterArray[j];
                    result.add(comb);
                }
    
            }
        }
        return result;
    }

Log in to reply
 

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