Using java stream & reduce


  • 0
    M
    public class Solution {
        public List<String> letterCombinations(String digits) {
            List<List<String>> input = new ArrayList<>();
            for (char c : digits.toCharArray()) {    
                if (c == '2') input.add(Arrays.asList("a", "b", "c"));
                else if (c == '3') input.add(Arrays.asList("d", "e", "f"));
                else if (c == '4') input.add(Arrays.asList("g", "h", "i"));
                else if (c == '5') input.add(Arrays.asList("j", "k", "l"));
                else if (c == '6') input.add(Arrays.asList("m", "n", "o"));
                else if (c == '7') input.add(Arrays.asList("p", "q", "r", "s"));
                else if (c == '8') input.add(Arrays.asList("t", "u", "v"));
                else if (c == '9') input.add(Arrays.asList("w", "x", "y", "z"));
            }    
            
            return input.stream().reduce((a,b) -> multiply(a, b)).orElse(Collections.EMPTY_LIST);
            
        }
        
        public List<String> multiply(List<String> a, List<String> b) {
            List<String> result = new ArrayList<>();
            for (String aa : a) {
                for (String bb : b) {
                    result.add(aa + bb);
                }
            }
            return result;
        }
        
        
    }
    
    

Log in to reply
 

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