A iterative JAVA solution using LinkedList


  • 0
    _
    public List<String> letterCombinations(String digits) {
            String[][] keys= {{"a","b","c"},{"d","e","f"},{"g","h","i"},{"j","k","l"},{"m","n","o"},{"p","q","r","s"},{"t","u","v"},{"w","x","y","z"}};
            char[] digitsAsChars = String.valueOf(digits).toCharArray();
            int[] p_digits = new int[digitsAsChars.length];
    
            if (p_digits.length == 0) return new ArrayList<>();
            for(int i=0; i<digitsAsChars.length; i++) p_digits[i] = digitsAsChars[i]-48;
    
            LinkedList<String> res= new LinkedList<>(Arrays.asList(keys[p_digits[0]-2]));
    
            for(int i = 1; i<p_digits.length;i++){
                int limit = res.size();
                for(String character : keys[p_digits[i]-2])
                    for(int j = 0; j < limit; j++)
                        res.add(res.get(j)+ character);
                for(int k = 0; k < limit; k++) res.removeFirst();
            }
            return res;
        }
    

Log in to reply
 

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