A somewhat modular solution (2ms | Java)


  • 0
    S
    public class Solution {
        
        public boolean checkLetter(String word, Set<Character> curr_row) {
            char[] word_array = word.toCharArray();
            for(int i = 0; i < word_array.length; ++i) {
                Character currentCharacter = word_array[i];
                if(curr_row.contains(currentCharacter) == false) {
                    return false;
                }
            }
            return true;
        }
        
        public String[] findWords(String[] words) {
            
            ArrayList<String> ret = new ArrayList<String>();
            
            Character first_set[] = {'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P'};
            Character second_set[] = {'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L'};
            Character third_set[] = {'Z', 'X', 'C', 'V', 'B', 'N', 'M'};
            
            Set<Character> first_row = new HashSet<Character>(Arrays.asList(first_set));
            Set<Character> second_row = new HashSet<Character>(Arrays.asList(second_set));
            Set<Character> third_row = new HashSet<Character>(Arrays.asList(third_set));
            
            for(int i = 0; i < words.length; ++i) {
                String curr_word = words[i];
                Character first_letter = curr_word.charAt(0);
                boolean checker = false;
                
                if(first_row.contains(Character.toUpperCase(first_letter))) {
                    checker = checkLetter(curr_word.toUpperCase(), first_row);
                } else if(second_row.contains(Character.toUpperCase(first_letter))) {
                    checker = checkLetter(curr_word.toUpperCase(), second_row);
                } else {
                    checker = checkLetter(curr_word.toUpperCase(), third_row);
                }
                
                if(checker == true) {
                    ret.add(curr_word);
                }
            }
            // String[] myArray = myArrayList.toArray(new String[myArrayList.size()]);
            return ret.toArray(new String[ret.size()]);
        }
    }
    

    The checkLetter can really be a static method, but I just kept it as it is. The key is to convert everything to uppercase and just check against uppercase (you can do the same for lowercase).

    If we treat the length of the input array "words" as N and we treat the number of characters in each "word" as M, then I believe the runtime for this is O(NM)


Log in to reply
 

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