Java simple solution using pre-processing


  • 0
    M

    A very simple solution creating a dictionary of rows and then searching for all characters of a word if the first one was found on that set. Runtime: 4 ms

    public class Solution {
        public String[] findWords(String[] words) {
            List<Set<Character>> dict = new ArrayList<>();
            populateDict(dict);
            List<String> result = new ArrayList<>();
            for (int i = 0; i < words.length; i++) {
                if (singleRow(words[i], dict)) {
                    result.add(words[i]);
                }
            }
            return result.toArray(new String[0]);
        }
        
        private boolean singleRow(String word, List<Set<Character>> dict) {
            for (int i = 0; i < dict.size(); i++) {
                Set<Character> row = dict.get(i);
                if (row.contains(Character.toUpperCase(word.charAt(0)))) {
                    for (int j = 1; j < word.length(); j++) {
                        if (!row.contains(Character.toUpperCase(word.charAt(j)))) {
                            return false;
                        }
                    }
                    return true;
                }
            }
            return false;
        }
        
        private void populateDict(List<Set<Character>> dict) {
            Set<Character> row1Set = new HashSet<>();
            row1Set.add('Q');
            row1Set.add('W');
            row1Set.add('E');
            row1Set.add('R');
            row1Set.add('T');
            row1Set.add('Y');
            row1Set.add('U');
            row1Set.add('I');
            row1Set.add('O');
            row1Set.add('P');
            dict.add(row1Set);
    
            Set<Character> row2Set = new HashSet<>();
            row2Set.add('A');
            row2Set.add('S');
            row2Set.add('D');
            row2Set.add('F');
            row2Set.add('G');
            row2Set.add('H');
            row2Set.add('J');
            row2Set.add('K');
            row2Set.add('L');
            dict.add(row2Set);
    
            Set<Character> row3Set = new HashSet<>();
            row3Set.add('Z');
            row3Set.add('X');
            row3Set.add('C');
            row3Set.add('V');
            row3Set.add('B');
            row3Set.add('N');
            row3Set.add('M');
            dict.add(row3Set);
        }
    }
    

Log in to reply
 

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