Simple, easy to understand Java Solution


  • 0
    F

    Idea

    • Preload a hashmap where the key is the alphabetic character and the value is the row it is on the keyboard
    • Use a valid flag to keep track of whether or not a word is a valid result
    • For each word, set the row to the first character of the word. Check if the remaining characters are all on the same row, using the value within the hashmap. If they differ, set the flag to false
    • If the flag is true, then go ahead and add the word to your list of results

    Solution:

        public String[] findWords(String[] words) {
            char[][] keyboard = {
                {'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'},
                {'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'},
                {'z', 'x', 'c', 'v', 'b', 'n', 'm'}
            };
            
            HashMap<Character, Integer> map = new HashMap<>();
            ArrayList<String> tempResults = new ArrayList<>();
            
            for (int i = 0; i < keyboard.length; i++) {
                for (int j = 0; j < keyboard[i].length; j++) {
                    map.put(keyboard[i][j], i);
                }
            }
            
            
            for (String word : words) {
                char[] chars = word.toLowerCase().toCharArray();
                boolean valid = true;
                // get the row of the first character
                int row = map.get(chars[0]);
                for (char c : chars) {
                    if (row != map.get(c)) {
                        valid = false;
                        break;
                    }
                }
                
                if (valid) {
                    tempResults.add(word);
                }
            }
            
            return tempResults.toArray(new String[tempResults.size()]);
        }
    

Log in to reply
 

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