Java using array lookup


  • 0
    E
    public class Solution {
        
        public String[] findWords(String[] words) {
            int[] keyboard = new int[26];
            populateKeyboard(keyboard);
            List<String> validList = new ArrayList<>();
            for(String s : words) {
                if(valid(s, keyboard)) validList.add(s);
            }
            return validList.toArray(new String[validList.size()]);
        }
        
        public boolean valid(String s, int[] keyboard) {
            int row = -1;
            for(Character c : s.toCharArray()) {
                Character cUpper = Character.toUpperCase(c);
                if(row == -1) row = keyboard[charToInt(cUpper)];
                else {
                    if(row != keyboard[charToInt(cUpper)]) return false;
                }
            }
            return true;
        }
        
        private void populateKeyboard(int[] keyboard) {
            populateRow(keyboard, "QWERTYUIOP", 1);
            populateRow(keyboard, "ASDFGHJKL", 2);
            populateRow(keyboard, "ZXCVBNM", 3);
        }
        
        private void populateRow(int[] keyboard, String str, int row) {
            for(Character c : str.toCharArray()) {
                keyboard[charToInt(c)] = row;
            }
        }
        
        private int charToInt(Character c) {
            return c - 'A';
        }
    }
    

Log in to reply
 

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