Easy to understand Java


  • 0
    C

    Time: O(N K) where N is the # of words and K is average length of each word.
    Space: O(N) where N is the # of words.

    public class Solution {
        public String[] findWords(String[] words) {
            char[] top = {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'};
            char[] mid = {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'};
            char[] bot = {'z', 'x', 'c', 'v', 'b', 'n', 'm'};
            
            Set<Character> topSet, midSet, botSet;
            topSet = new HashSet<>();
            midSet = new HashSet<>();
            botSet = new HashSet<>();
            for (char c : top) topSet.add(c);
            for (char c : mid) midSet.add(c);
            for (char c : bot) botSet.add(c);
            
            List<String> list = new ArrayList<>();
            for (String word : words) {
                char[] letters = word.toLowerCase().toCharArray();
                boolean inTop = true, inMid = true, inBot = true;
                for (int i = 0; i < letters.length; i++) {
                    char elem = letters[i];
                    if (!topSet.contains(elem)) inTop = false;
                    if (!midSet.contains(elem)) inMid = false;
                    if (!botSet.contains(elem)) inBot = false;
                }
                if (inTop || inMid || inBot) list.add(word);
            }
            String[] result = new String[list.size()];
            for (int i = 0; i < result.length; i++) {
                result[i] = list.get(i);
            }
            return result;
        }
    }

Log in to reply
 

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