LeetCode 500: Keyboard Row

Problem Description

Explanation:

  • Create a set for each row of the keyboard with the characters in that row.
  • Iterate over each word in the input array and check if all characters in the word belong to the same row of the keyboard.
  • If a word meets the criteria, add it to the result list.

Time Complexity: O(n * m) where n is the number of words and m is the average length of a word. Space Complexity: O(1) since the size of the keyboard rows is fixed.

:

Solutions

class Solution {
    public String[] findWords(String[] words) {
        String[] rows = new String[]{"qwertyuiop", "asdfghjkl", "zxcvbnm"};
        List<String> result = new ArrayList<>();
        
        for (String word : words) {
            if (checkWordInRow(word.toLowerCase(), rows)) {
                result.add(word);
            }
        }
        
        return result.toArray(new String[result.size()]);
    }
    
    private boolean checkWordInRow(String word, String[] rows) {
        for (String row : rows) {
            boolean inSameRow = true;
            for (char c : word.toCharArray()) {
                if (row.indexOf(c) == -1) {
                    inSameRow = false;
                    break;
                }
            }
            if (inSameRow) {
                return true;
            }
        }
        return false;
    }
}

Loading editor...