Verbose Java solution (3ms)


  • 2
    1. Find which row does the first character belong to.
    2. Verify rest of the characters.
    public class Solution {
        private static String[] strs = {"qwertyuiop", "asdfghjkl", "zxcvbnm"};
        
        public String[] findWords(String[] words) {
            List<String> res = new ArrayList<>();
            
            for (String word : words) {
                if (word.length() == 0) continue;
                
                int row = 0;
                for (; row < 3; row++) {
                    if (inRow(word.charAt(0), row)) break;
                }
                if (row >= 3) continue;
                
                boolean flag = true;
                for (int i = 1; i < word.length(); i++) {
                    if (!inRow(word.charAt(i), row)) {
                        flag = false;
                        break;
                    }
                }
                
                if (flag) {
                    res.add(word);
                }
            }
            
            return res.toArray(new String[res.size()]);
        }
        
        private boolean inRow(char c, int row) {
            if (strs[row].contains(Character.toLowerCase(c)+"")) return true;
            else return false;
        }
    }
    

  • 0
    S

    @shawngao same idea, a bit less verbose. 6ms.

    public class Solution {
    
        private List<List<Character>> keyboardLine = Arrays.asList(Arrays.asList('q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'),
                                                                   Arrays.asList('a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'),
                                                                   Arrays.asList('z', 'x', 'c', 'v', 'b', 'n', 'm')) ;
    
        public String[] findWords(String[] words) {
    
            List<String> validWords = new ArrayList<>();
            for (String word : words) {
                if (isOneLine(word, keyboardLine.get(0))) validWords.add(word);
                else if (isOneLine(word, keyboardLine.get(1))) validWords.add(word);
                else if (isOneLine(word, keyboardLine.get(2))) validWords.add(word);
            }
            return validWords.toArray(new String[validWords.size()]);
        }
    
        private boolean isOneLine(String word, List<Character> keyboardLine) {
            for (int j = 0; j < word.length(); j++) {
                if (!keyboardLine.contains(word.toLowerCase().charAt(j))) {
                    return false;
                }
            }
            return true;
        }
    }

Log in to reply
 

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